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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。