เมธอด process.chdir() ใช้สำหรับเปลี่ยนไดเร็กทอรีปัจจุบันของกระบวนการ Node.js มันจะส่งข้อยกเว้นหากมีข้อผิดพลาดเกิดขึ้นหรือกระบวนการล้มเหลว แต่จะไม่ส่งคืนการตอบกลับเมื่อสำเร็จ ตัวอย่างเช่น อาจล้มเหลวได้เมื่อไม่มีไดเร็กทอรีที่ระบุ
ไวยากรณ์
process.chdir(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\node>> 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\node>> 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' }