My node.js server doesn't work when launched from another directory

I’m trying to get my node.js server to launch on startup. If I’m in my server folder and type:

node server.js

It runs just fine and launches python scripts that are in the same folder.

But if I run it from outside that directory or from an init script, like this:

node /home/servers/server.js

It starts, and receives calls, but is not running the python scripts as it is supposed to.

Does anyone know what is going on and how I can fix it? Thanks.

41 thoughts on “My node.js server doesn't work when launched from another directory”

  1. When you run node, it references all filesystem calls from the directory node was called from, instead of the directory that app.js is in, so if you’re trying to require('./myfile'), myfile.js will need to be in the directory you’re running node in.

    Run this simple script from different directories to see it in action (it runs ls, lovingly copied from here):

    var sys = require('sys')
    var exec = require('child_process').exec;
    function puts(error, stdout, stderr) { sys.puts(stdout) }
    exec("ls -la", puts);

    As to your Python problem, you should develop an empirical location to call app.js from, and use that when locating scripts.

  2. You can also change the directory to ensure you’re where you need to be. Just add something like this to the top of your file:

    __dirname points to the directory containing the current file. For this example I will be assuming the following repo structure:


    And inside index.js I will put:

    const path = require('path');

Leave a Comment