{"id":1930,"date":"2013-08-27T20:21:00","date_gmt":"2013-08-28T01:21:00","guid":{"rendered":"http:\/\/www.wiredprairie.us\/blog\/?p=1930"},"modified":"2022-06-29T10:21:02","modified_gmt":"2022-06-29T15:21:02","slug":"sending-a-socket-to-a-forked-process-in-node-js","status":"publish","type":"post","link":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/1930","title":{"rendered":"Sending a socket to a forked process in Node.JS"},"content":{"rendered":"\n
If you want to fork a process in Node and pass a socket, the current Node documentation has a rather odd example, so I\u2019ve simplified it here for my own sanity (further complicated by the fact that the WebStorm debugger can\u2019t debug a forked Node.JS process, which confused me for too long). Hopefully someone else finds this useful at some point.<\/p>\n\n\n\n
Step 1, in a file called app.js:<\/strong><\/p>\n\n\n\nvar<\/span> child = require('child_process'<\/span>).fork('socket_handler.js'<\/span>);\n\n\/\/ Open up the server and send sockets to child<\/span>\nvar<\/span> server = require('net'<\/span>).createServer();\n\nserver.on('connection'<\/span>, function<\/span> (socket) {\n child.send('socket'<\/span>, socket);\n server.getConnections(function<\/span>(err, count) {\n console.log(\"Connections: \"<\/span> + count);\n });\n});\nserver.listen(1337);\n