Skip to content

Instantly share code, notes, and snippets.

@dshaw
Created July 12, 2012 00:57
Show Gist options
  • Select an option

  • Save dshaw/3094870 to your computer and use it in GitHub Desktop.

Select an option

Save dshaw/3094870 to your computer and use it in GitHub Desktop.

Revisions

  1. dshaw created this gist Jul 12, 2012.
    40 changes: 40 additions & 0 deletions replify.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    var fs = require("fs")
    , net = require("net")
    , repl = require("repl")

    module.exports = function replify (name, ctx) {
    var repl_path = "/tmp/" + name + ".sock"
    ctx || (ctx = {})

    fs.unlink(repl_path, function () {
    // intentionally not listening for the error. either way, we're good.

    net.createServer(function repl_onrequest(socket) {
    var repl_opt = {
    prompt: name + "> "
    , input: socket
    , output: socket
    , terminal: true
    , useGlobal: false
    },
    r = null

    socket.columns = 132 // Set screen width for autocomplete. You can modify this locally in your repl.

    if (fs.exists) { // if `fs.exists` exists, then it's node v0.8
    r = repl.start(repl_opt)
    r.on('exit', function () {
    socket.end()
    })
    } else {
    r = repl.start(repl_opt.prompt, socket)
    }

    r.context.socket = socket
    Object.keys(ctx).forEach(function (key) {
    // don't pave me, bro!
    if (!r.context[key]) r.context[key] = ctx[key]
    })
    }).listen(repl_path)
    })
    }