I have a simple node js server and I would like to connect to another socket, read data, and return it to the client.
http.createServer(function(req, res){
var sock = new Socket();
sock.connect(80, "www.google.com", function(){
console.log("Connected to google..");
sock.write("GET /\r\n\r\n");
});
sock.on("data", function(data){
console.log(data.toString());
res.writeHead(404, {"Content-type": "text/plain"});
res.write(data, "binary");
res.end();
sock.end();
});
sock.on("end", function(){
console.log("Disconnected from socket..");
});
}, 8080);
But this obviously doesn't work because the call to data callback is asynchronous.
So how can I accomplish this with node js?
After adding the missing "require" statements and the server.listen() call to get the script to run, it works fine for me:
var http = require('http');
var Socket = require('net').Socket;
var server = http.createServer(function(req, res){
var sock = new Socket();
sock.connect(80, "www.google.com", function(){
console.log("Connected to google..");
sock.write("GET /\r\n\r\n");
});
sock.on("data", function(data){
console.log(data.toString());
res.writeHead(404, {"Content-type": "text/plain"});
res.write(data, "binary");
res.end();
sock.end();
});
sock.on("end", function(){
console.log("Disconnected from socket..");
});
});
server.listen(8080);