Search code examples
javascriptnode.jstcptcpclientnetcat

Node.js equivalent of: echo 'message' | nc -v <server> <port>


Trying to send a plain text message in a Node.js app in the same way I would from the terminal using 'nc', i.e.

echo "a.random.test" | nc -v <some_domain> <some_port>

However not able to do so. I have tried using the const 'netcat/client' npm module with no luck. Here is the link to documentation for that module https://github.com/roccomuso/netcat and below is some of my current attempts. It seems that the connection is made (confirmed due the callback firing) however extra padding is in the message and my intended plaintext message of "a.random.test" is not being received as is, "a.random.test".

const nclient = require('netcat/client')
const nc2 = new nclient()

nc2
.addr('x.x.x.x') // the ip
.port(2003) // the port 
.connect()
.send(`a.random.test`, () => console.log(`connection made and message sent`))

I have also tried with good 'ol "net" module sockets below with no luck.

var net = require('net');
var client = new net.Socket();

client.connect(2003, 'x.x.x.x', function() {
    console.log(`sending to server: a.random.test`)
    client.write(`a.random.test`)
});

Any help sending plain text to a given port in node.js would be much appreciated... I feel like it should be easy - I've spent more time than I'd like to admit trying todo so! Thank you very much in advance.


Solution

  • echo appends a newline to the string, which you're not adding in your JS code:

    var net = require('net');
    var client = new net.Socket();
    
    client.connect(2003, 'x.x.x.x', function() {
        console.log(`sending to server: a.random.test`)
        client.write(`a.random.test\n`)
                                   ^^
    });