Javascript 无法从node.js中的函数内部更改目录
我有以下代码:Javascript 无法从node.js中的函数内部更改目录,javascript,node.js,chdir,Javascript,Node.js,Chdir,我有以下代码: 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() {
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()更改目录吗?我需要在这些函数之间传递一些信息吗
谢谢。试试这个,这样我们就可以了解有关错误的更多信息
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()引用调用node命令的目录。它不引用正在执行的文件的目录
__dirname是指正在执行的文件所在的目录
因此,下次使用./、process.cwd()或_udirname时要小心。确保您使用的正是您想要的。您使用了相对目录路径
AA/BB
,通过调用start()
进程已经chdir
相对于cwd
,/AA/BB
发送到该目录
因此,调用
tick()
将使其在当前cwd/AA/BB
中查找AA/BB
,例如,/AA/BB/AA/BB
,它不存在。in line-self.tick(进程);您正在传递一个变量进程,但“this.tick=function(){”没有任何参数。我尝试向函数中添加参数并使用它们,但没有任何帮助:(是这样吗?将进程传递给函数并以某种方式使用它?是的,您是对的:(我正在检查_dirname,但它仍然指向父目录,所以我假设chdir不工作。_dirname肯定是其他意思。谢谢!谢谢!我认为_dirname也显示当前目录,这是我在测试时出错的地方。)。