📜  Node.js process.chdir() 方法

📅  最后修改于: 2022-05-13 01:56:21.632000             🧑  作者: Mango

Node.js process.chdir() 方法

process.chdir() 方法是进程模块的内置应用程序编程接口,用于更改当前工作目录。

句法:

process.chdir( directory )

参数:此方法接受上面提到的单个参数,如下所述:

  • directory:必填参数,指定要更改当前工作目录的目录的路径。

返回值:此方法成功时不返回任何值,但如果更改目录失败,指定“没有这样的文件或目录”,则抛出异常。

下面的例子说明了在 Node.js 中process.chdir() 方法的使用:

示例 1:

// Node.js program to demonstrate the     
// process.chdir() Method
   
// Include process module
const process = require('process');
  
try {
  
  // Change the directory
  process.chdir('../os');
  console.log("directory has successfully been changed");
} catch (err) {
      
  // Printing error if occurs
  console.error("error while changing directory");
}

输出:

directory has successfully been changed

示例 2:

// Node.js program to demonstrate the     
// process.chdir() Method
   
// Include process module
const process = require('process');
  
// Printing current directory
console.log("current working directory: "
          + process.cwd());
try {
      
  // Change the directory
  process.chdir('../os');
  console.log("working directory after "
          + "changing: " + process.cwd());
} catch (err) {
    
  // Printing error if occurs
  console.error("error occured while "
        + "changing directory: " + err);
}

输出:

current working directory: C:\nodejs\g\process
working directory after changing: C:\nodejs\g\os

注意:上面的程序将使用node filename.js命令编译和运行。

参考: https://nodejs.org/api/process.html#process_process_chdir_directory