Skip to content

Commit

Permalink
refs #5: add - basic repl for node.js 4.2.3
Browse files Browse the repository at this point in the history
  • Loading branch information
adrysn committed Dec 22, 2015
1 parent 05fb2ff commit 2aad0ad
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 11 deletions.
2 changes: 1 addition & 1 deletion nodejs4.2.3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"main": "/home/sorna/run.js",
"author": "Jonghyun Park <adrysn@lablup.com>",
"dependencies": {
"express": "4.x",
"process": "*",
"zmq": "2.14.0"
}
}
86 changes: 76 additions & 10 deletions nodejs4.2.3/run.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,76 @@
var express = require('express');
var PORT = 2001;

var app = express();
app.get('/', function(req, resp) {
resp.send('Hello world\n');
});

app.listen(PORT);
console.log('success!! port: ', PORT);
var main = function() {
var process = require('process');
var zmq = require('zmq');
var socket = zmq.socket('rep');
var port = 'tcp://*:2001';

// refs: https://gist.github.com/pguillory/729616
function hook_stdout(callback) {
var old_stdout_write = process.stdout.write;
process.stdout.write = (function(write) {
return function(string, encoding, fd) {
write.apply(process.stdout, arguments);
callback(string, encoding, fd);
};
})(process.stdout.write);
return function() {
process.stdout.write = old_stdout_write;
}
}

function hook_stderr(callback) {
var old_stderr_write = process.stderr.write;
process.stderr.write = (function(write) {
return function(string, encoding, fd) {
write.apply(process.stderr, arguments);
callback(string, encoding, fd);
};
})(process.stderr.write);
return function() {
process.stderr.write = old_stderr_write;
}
}

function execute(code) {
eval(code);
}

process.chdir('/home/work');

socket.on('message', function(code_id, code) {
var stdout = '';
var stderr = '';
var exceptions = []; // exceptions not supported yet
var unhook_stdout = hook_stdout(function(string, encoding, fd) {
stdout += string;
});
var unhook_stderr = hook_stderr(function(string, encoding, fd) {
stderr += string;
});
execute(code.toString());
var result = {
'stdout': stdout,
'stderr': stderr,
'exceptions': exceptions
};
socket.send(JSON.stringify(result));
unhook_stdout();
unhook_stderr();
});

socket.on('SIGINT', function() {
socket.close();
});

socket.bind(port, function(err) {
if (err) {
throw err;
} else {
console.log('Serving at ' + port + '...');
}
});
}

if (require.main === module) {
main();
}

0 comments on commit 2aad0ad

Please sign in to comment.