无法从 node.js 中的函数内部更改目录

Cannot change directory from inside a function in node.js

我有以下代码:

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);
    }
}

我从另一个 class 调用 start() 是这样的:

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

有人可以解释为什么我可以从 start() 更改目录,但不能从 tick() 更改目录吗?我需要在这些函数之间传递一些东西吗?

谢谢。

试试这个,以便我们可以捕获有关错误的更多信息

 this.tick = function() {
   try {
    console.log('__dirname: ', __dirname);
    console.log("The directory from which node command is called is " + process.cwd());
    process.chdir("root_path/AA/BB");
}
catch (err) {
        //handle the error here
}
}

只要确保提供正确的根路径即可。

./ 和 process.cwd() 指的是调用节点命令的目录。它不是指正在执行的文件的目录。

__dirname指的是正在执行的文件所在的目录。

所以下次使用./、process.cwd() 或__dirname 时要小心。确保您使用的正是您想要的。

您使用了相对目录路径 AA/BB,通过调用 start() 进程已经 chdired 到相对于 cwd./AA/BB 的那个目录.

随后调用 tick() 将使其在当前 cwd ./AA/BB 中查找 AA/BB,例如./AA/BB/AA/BB,不存在。