【问题标题】:Cannot change directory from inside a function in node.js无法从 node.js 中的函数内部更改目录
【发布时间】:2018-06-19 12:58:35
【问题描述】:

我有以下代码:

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

我像这样从另一个类调用 start():

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

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

谢谢。

【问题讨论】:

  • 在线 - self.tick(process);您正在传递一个变量进程,但“this.tick = function() { ”没有任何参数。
  • 我尝试向函数添加参数并使用它们,但没有帮助:(这是要走的路吗?将进程传递给函数并以某种方式使用它?

标签: javascript node.js chdir


【解决方案1】:

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

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

【讨论】:

  • 是的,你是对的 :( 我正在检查 __dirname 并且它仍然指向父目录,所以我认为 chdir 不起作用。__dirname 一定有别的意思。谢谢!
【解决方案2】:

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

 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 时要小心。确保您使用的正是您想要的。

【讨论】:

  • 谢谢!我以为 __dirname 也显示了当前目录,那是我在测试时出错的地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多