Last Updated: February 25, 2016
· kytwb

Detect if a script has been forked in NodeJS

On the project I'm currently working on, I try to handle all the weird behaviors the future users could have; one could be trying to run random scripts as stand-alone programs when they're not. Immediately, you will think of module.parent; unfortunately, this only indicate if your script has been called using require() or not. What if the only execution context of your script resides in a fork(), like:

this.worker = childProcess.fork(__dirname + '/shard.starter.js');

Where shard.starter.js looks like:

(function ShardStarter() {
    // Insert code here.

Well, to avoid shard.starter.js to be run as a stand-alone here, just check if process.send exists. If it does, it means your script has been forked. Otherwise, your script is being executed as a stand-alone.

if (!process.send)
(function ShardStarter() {
    // Insert code here.

Why? Simply because process.send is exclusive to child process (see process and child_process in the documentation for further details).

Note: I wrote this tip because there's no accurate answer popping up in Google when searching for the title terms. Hoping it will be indexed and pop up for future people searching with these terms.

1 Response
Add your response


Could also have used cluster.isMaster but it involves an extra require of cluster, which I include nowhere else in my project.

over 1 year ago ·