Search code examples
javascriptnode.jschdir

Cannot change directory from inside a function in node.js


I have the following code:

module.exports = function(db, threads) {
    var self = this;
    this.tick = function() {
        //process.chdir("AA/BB"); // This line gives error "Error: ENOENT: no such file or directory, uv_chdir"
    }

    this.start = function() {
        process.chdir("AA/BB"); // this works
        console.log("The new working directory is " + process.cwd());
        self.tick(process);
    }
}

I call start() from another class like this:

var man = require('./temp.js');
var manager = new man(db, threads);
manager.start();

Can somebody explain why I can change directory from start(), but not from tick()? Do I need to pass something between these functions?

Thanks.


Solution

  • You used relative dir path AA/BB, by calling start() the process has already chdired to that directory relative to the cwd, ./AA/BB.

    Calling tick() consequently will make it look up AA/BB in the current cwd ./AA/BB, e.g. ./AA/BB/AA/BB, which doesn't exists.