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
相关用法
注:本文由纯净天空筛选整理自anwesha0107大神的英文原创作品 Node.js | process.chdir() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。