Created
October 27, 2012 20:47
-
-
Save mattjj/3966173 to your computer and use it in GitHub Desktop.
a tiny node.js server that routes stdin to a websocket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var socket = io.connect(window.location.host); | |
var received; | |
socket.on('data', function (data) { | |
received = JSON.parse(data); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()); } | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can run the server with
some-neato-process | node websocketcat.js
and include the browser socket part with
or something...