Search code examples
node.jsplesk

Nodejs module.parent condition not working on ubuntu server


I am working on an existing project and found this piece of code in my app.js

//if (!module.parent) {
  // Server listen
  app.listen(mysettings.port, function () {
    console.log(`Server ready at ${ENV}:${mysettings.port}`);
  });
//}

When I run locally, app.listen hits and my project runs, when I upload my project on a ubuntu server, the project does not run, but times out. When I comment out the condition on ubuntu the project runs perfectly. I know on my localhost, module.parent is null.

Any help would be apperciated.


Solution

  • This maybe works for you:

    if ((!module.parent) || (("exports" in module.parent) && ("PhusionPassenger" in module.parent.exports))) {
      // Server listen
      app.listen(mysettings.port, function () {
        console.log(`Server ready at ${ENV}:${mysettings.port}`);
      });
    }
    

    module.parent is null when your app.js is called directly from node just as in node app.js.

    I believe Plesk utilizes PhusionPassenger under the hood (at least Plesk official node.js extension which is probably your case). Being this the case, your app is probably called with the command passenger start --app-type node --startup-file app.js which pre-loads a script node-loader.js before yours, which becomes your module.parent.

    If you want the same behaviour for both direct node and Passenger's call, then you have to replace every (!module.parent) filter in your code with (!module.parent) || (("exports" in module.parent) && ("PhusionPassenger" in module.parent.exports)). By doing this you will keep avoiding the situations the original developer probably intended to avoid.