Phần 5: File System (P3)
Các phần trước:
Phần 2: Tạo Modules trong Node.JS
Tạo thư mục
Để tạo một thư mục mới, ta dùng phương thức mkdir():
fs.mkdir(path,function(err) {} )
//path là đường dẫn đến thư mục
Ví dụ, ta tạo một folder test mới như sau:
var fs = require("fs");
fs.mkdir('./test',function(err){
if (err) {
return console.error(err);
}
console.log("Tạo thư mục thành công!");
});
//Kết quả
//Tạo thư mục thành công!
Đọc thư mục
Để đọc một thư mục ta dung cú pháp sau:
fs.readdir(path, function(err,files) {} )
//path là đường dẫn đến thư mục
Ví dụ:
var fs = require("fs");
fs.readdir("./test",function(err, files){
if (err) {
return console.error(err);
}
files.forEach( function (file){
console.log( file );
});
});
//Kết quả
//test.txt
//test1
//test2
//test3
Xóa thư mục
Để xóa thư mục, ta dùng cú pháp sau:
fs.rmdir(path, function(err) {} )
//path là đường dẫn đến thư mục
Ví dụ, chúng ta sẽ xóa thư mục test3 trong thư mục test ở trên.
var fs = require("fs");
//Xóa thư mục test3
fs.rmdir("./test/test3",function(err){
if (err) {
return console.error(err);
}
console.log("Đọc thư mục");
});
//Đọc thư mục test sau khi xóa thư mục test3
fs.readdir("./test",function(err, files){
if (err) {
return console.error(err);
}
files.forEach( function (file){
console.log( file );
});
});
//Kết quả
//Đọc thư mục
//text.txt
//text1
//text2
Một số phương thức khác
Các bạn tham khảo tại https://nodejs.org/api/fs.html
Bình luận