Node.js 中的 process.chdir() 方法
process.chdir() 方法用于更改 Node.js 进程的当前目录。如果发生任何错误或进程失败,它将抛出异常,但不会在成功时返回任何响应。例如:当指定的目录不存在时,它可能会失败。
语法
process.chdir(directory)
参数
directory – 这将包含该目录的名称,该目录将更新为之前的目录名称。
示例
创建一个名为 – chdir.js 的文件并将以下代码片段复制到其中。创建文件后,使用以下命令运行此代码,如下例所示 &Minus;
node chdir.js
chdir.js
// Node.js program to demonstrate the use of process.chdir()
// Importing the process module
const process = require('process');
// Printing present working Directory
console.log("Present working directory: " + process.cwd());
try {
// Updating with the New directory
process.chdir('../tutorialspoint');
console.log("Updated working directory is: " + process.cwd());
} catch (err) {
// Printing error if any occurs
console.error("error occured while " + "changing directory: " + err);
}输出
C:\home
ode>> node chdir.js Present working directory: /home/mayankaggarwal/mysql-test Updated working directory is: /home/mayankaggarwal/tutorialspoint
示例
让我们再看一个例子。
// Node.js program to demonstrate the use of process.argv
// Importing the process module
const process = require('process');
try {
// Changing the directory with below namey
process.chdir('../not/tutorialspoint');
console.log("New Directory has been succesfully updated");
} catch (err) {
// Printing error if occurs
console.error("Error while changing directory", err);
}输出
C:\home
ode>> node chdir.js Error while changing directory { Error: ENOENT: no such file or directory, chdir '../not/tutorialspoint' at process.chdir (internal/process/main_thread_only.js:31:12) at Object.<anonymous> (/home/mayankaggarwal/mysql-test/process.js:9:9) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3) errno: -2, code: 'ENOENT', syscall: 'chdir', path: '../not/tutorialspoint' }
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP