My problem in short involves trying to build a very simple TCP client (think Netcat) with node's net module. I have had success with sock.write('GET etc...), but when I try to use the readline module to dynamically send data, the servers I have tried to talk to either never respond, or don't respond how I would expect them to.
My suspicion is that the readline module is escaping escape characters such as \r\n, which causes my request to the servers to be improperly formatted. I have tried:
client.write(new Buffer(cmd))
But my basic TCP server is still interpreting /r/n as text. In fact, the native console interprets it as text.
Update: I have verified by using JSON.stringify on the terminal output that something is escaping escape characters (e.g. When I enter \r\n into the terminal the JSON.stringify -ed terminal input reads as \\r\\n). Maybe my terminal is doing it by default and this isn't at all a problem with node.js? I'm using Windows Powershell.
See my client script below for further clarification:
// Inspired and sourced from: http://www.hacksparrow.com/tcp-socket-programming-in-node-js.html
// ANSI escape code sequence for colors, etc. General Form: "\x1b[Nm" Where N is a number.
// For http requests, see http://stackoverflow.com/questions/6686261/what-at-the-bare-minimum-is-required-for-an-http-request
//For IRC protocol see https://news.ycombinator.com/item?id=2071318
var net = require('net');
var fs = require('fs');
var readline = require('readline');
var host = 'localhost';
var port = 6667;
var client = new net.Socket();
client.connect(port, host, function() {
console.log('CONNECTED TO: ' + host + ':' + port + '\n');
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('USER foo bar batz boo\r\nNICK test345\r\n');
// client.write('JOIN #mae\r\n');
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', function(cmd) {
var bufferCommand = new Buffer(cmd)
console.log('bufferCommand = ' + bufferCommand);
client.write(bufferCommand);
});
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
var fs = require('fs');
fs.appendFile("log.txt", data, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
});
// Catches error if no TCP server to answer request.
client.on('error', function(error) {
console.log(error);
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
All help and criticism appreciated!