Write After End error in node.js webserver

后端 未结 3 1035
醉梦人生
醉梦人生 2021-02-06 22:55

I am struggling with my node.js hobby project due to a \"write after end\" Error. I have a created a node.js webserver that amongst other things, sends commands received from a

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 23:34

    NodeJS is a non-blocking async platform.

    In your case,

    netSocket.write(messages);
    

    is an async method; therefore, netSocket.end() is called before write is complete.

    The correct use would be:

    netSocket.write(messages, function(err) { netSocket.end(); });
    

    The second argument here is a callback function that will be called once the 'write' method finishes its job.

    I would recommend you read/watch more about NodeJS, async styles and callbacks.

    Here is a great place to start: https://www.youtube.com/watch?v=GJmFG4ffJZU

    And of course, the NodeJS API docs regarding net sockets.

提交回复
热议问题