Phương thức process.chdir() dùng để thay đổi thư mục làm việc hiện tại của tiến trình Node.js. Ném ngoại lệ nếu lỗi (ví dụ thư mục không tồn tại), không trả về giá trị khi thành công.
Cú pháp
process.chdir(directory)
Tham số
directory – Tên thư mục mới sẽ thay thế thư mục hiện tại.
Ví dụ
Tạo file chdir.js và sao chép mã. Chạy lệnh:
node chdir.js
chdir.js
// Chương trình Node.js minh họa process.chdir()
// Import module process
const process = require('process');
// In thư mục hiện tại
console.log("Thư mục hiện tại: " + process.cwd());
try {
// Thay đổi thư mục
process.chdir('../tutorialspoint');
console.log("Thư mục mới: " + process.cwd());
} catch (err) {
console.error("Lỗi khi thay đổi thư mục: " + err);
}
Kết quả
C:\home\node>> node chdir.js Thư mục hiện tại: /home/mayankaggarwal/mysql-test Thư mục mới: /home/mayankaggarwal/tutorialspoint
Ví dụ 2
Ví dụ xử lý lỗi khi thư mục không tồn tại.
// Chương trình Node.js minh họa process.chdir()
const process = require('process');
try {
process.chdir('../not/tutorialspoint');
console.log("Thư mục mới đã cập nhật thành công");
} catch (err) {
console.error("Lỗi khi thay đổi thư mục", err);
}
Kết quả
C:\home\node>> node chdir.js
Lỗi khi thay đổi thư mục { Error: ENOENT: no such file or directory, chdir '../not/tutorialspoint'
at process.chdir (internal/process/main_thread_only.js:31:12)
...
errno: -2, code: 'ENOENT', syscall: 'chdir', path: '../not/tutorialspoint' }