sunichi sunichi - 1 year ago 46
Node.js Question

JavaScript file can't work while the code work with node in Terminal

I start a java client listening on localhost:8887
And I try this

var net = require('net')
var coon = net.connect(8887,'')

in Terminal with node. The client get the message.
Then I write it into a file test.js and use 'node test.js' in the Terminal, but the client can't get the message. How can I solve this problem.

I add
in the code. When I run 'node test.js', it shows that 'undefined:undefined'

Answer Source

Chances are you type into the terminal slow enough for the connection to be made. When you run the whole script, you're attempting to write before there is a connection.

Use the 3rd connectionListener argument

const coon = net.connect(8887, 'localhost', () => {