Skip to content

Instantly share code, notes, and snippets.

@mattjj
Created October 27, 2012 20:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mattjj/3966173 to your computer and use it in GitHub Desktop.
Save mattjj/3966173 to your computer and use it in GitHub Desktop.
a tiny node.js server that routes stdin to a websocket
var socket = io.connect(window.location.host);
var received;
socket.on('data', function (data) {
received = JSON.parse(data);
});
// TODO something here is building up in the pipe and using virtual memory...
// maybe it's the weird use of readline?
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
rl = require('readline'),
url = require('url'),
path = require('path');
// process.stdin.resume(); // needed if not using readline
process.stdin.setEncoding('ascii');
app.listen(3000);
var mimeTypes = {
"html": "text/html",
"js": "text/javascript",
"css": "text/css"
};
function handler (req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
fs.readFile(filename, function (err,data) {
if (err) {
res.writeHead(500);
return res.end('Error');
}
var mimeType = mimeTypes[path.extname(filename).split('.')[1]];
res.writeHead(200, {'Content-Type':mimeType});
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
rl.createInterface(process.stdin, fs.createWriteStream('/dev/null'), null)
.on('line',function(chunk) {
if (chunk.length > 0) { socket.emit('data',chunk.toString()); }
});
});
@mattjj
Copy link
Author

mattjj commented Oct 28, 2012

can run the server with

some-neato-process | node websocketcat.js

and include the browser socket part with

<script src="js/websocketcat-receive.js"></script>

or something...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment