Hướng dẫn ghi file trong nodejs

http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Đọc ghi File Node.js Trong chương trước, bạn thấy sử dụng nhiều cú pháp require("fs") Vậy cú pháp để làm ? Đây cú pháp để khai báo fs Module để triển khai hoạt động File I/O Node.js Cú pháp sau: var fs = require("fs") Khái niệm Đồng vs Không đồng Node.js Mỗi phương thức fs Module có form đồng form không đồng Các phương thức không đồng nhận tham số cuối hàm callback thực thi kết thúc nhận tham số hàm callback để xử lý lỗi Việc sử dụng phương thức không đồng tốt phương thức đồng bộ, phương thức khơng đồng khơng khóa trình thực thi chương trình phương thức đồng có Ví dụ Để minh họa hoạt động I/O Node.js, bạn tạo input.txt có nội dung: VietJack la trang Web huong dan cac bai lap trinh hoan toan mien phi cho tat ca moi nguoi!!!!! Tạo main.js Như trình bày, phương thức fs Module có hai form đồng khơng đồng Để đọc liệu, sử dụng phương thức readFile() form không đồng readFileSync() form đồng để đọc liệu Hai phương thức nhận tham số tên file để đọc liệu từ var fs = require("fs"); // Phuong thuc doc file khong dong bo fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Phuong thuc doc file khong dong bo: " + data.toString()); }); // Phuong thuc doc file dong bo var data = fs.readFileSync('input.txt'); console.log("Phuong thuc doc file dong bo: " + data.toString()); console.log("Ket thuc chuong trinh"); Chạy main.js để xem kết quả: $ node main.js http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Kiểm tra kết quả: Phuong thuc doc file dong bo: VietJack la trang Web huong dan cac bai lap trinh hoan toan mien phi cho tat ca moi nguoi!!!!! Ket thuc chuong trinh Phuong thuc doc file khong dong bo: VietJack la trang Web huong dan cac bai lap trinh hoan toan mien phi cho tat ca moi nguoi!!!!! Phần trình bày chi tiết hoạt động File I/O thường gặp: Mở File Node.js Cú pháp Để mở file chế độ không đồng bộ, bạn sử dụng phương thức open() có cú pháp: fs.open(path, flags[, mode], callback) Tham số • path - Đây chuỗi biểu diễn tên file đường dẫn tới file • flags - Biểu diễn hành vi file mở Tất giá trị trình bày bảng • mode - Thiết lập chế độ cho file, chế độ thiết lập file tạo Giá trị mặc định 0666, tức readable writeable • callback - Hàm callback nhận hai tham số, ví dụ (err, fd) Các Flag sử dụng cho hoạt động Đọc/Ghi file Node.js Flag Miêu tả r Mở file để đọc Xuất Exception file không tồn r+ Mở file để đọc ghi Xuất Exception file không tồn rs Mở file để đọc chế độ đồng rs+ Mở file để đọc ghi, báo cho Hệ điều hành mở chế độ đồng http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     w wx w+ Mở file để ghi Nếu file khơng tồn tại, tạo file Giống 'w' hoạt động thất bại file khơng tồn (tức khơng tạo file mới) Mở file để đọc ghi Nếu file khơng tồn tại, tạo file wx+ Giống 'w+' hoạt động thất bại file không tồn a Mở file để append File tạo khơng tồn ax Giống 'a' hoạt động thất bại file không tồn a+ Mở file để đọc append File tạo khơng tồn ax+ Giống 'a+' hoạt động thất bại file không tồn Ví dụ Ví dụ sau minh họa cách mở file để đọc ghi Đầu tiên bạn tạo main.js có nội dung Nội dung file giống ví dụ trên, bạn ý vào phần flag sử dụng var fs = require("fs"); // Hoat dong mo File theo cach thuc khong dong bo console.log("Chuan bi mo File hien tai!"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File duoc mo cong!"); }); Chạy main.js để xem kết quả: $ node main.js Kiểm tra kết quả: Chuan bi mo File hien tai! File duoc mo cong! http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Lấy thơng tin File Node.js Cú pháp Để lấy thông tin file Node.js, bạn sử dụng phương thức stat() fs Module có cú pháp: fs.stat(path, callback) Chi tiết tham số • path - Đây chuỗi biểu diễn tên file đường dẫn tới file • callback - Là hàm callback nhận hai tham số (err, stats), stats đối tượng fs.Stats in ví dụ sau Ngồi thuộc tính quan trọng in ví dụ sau, lớp fs.Stats có số phương thức hữu ích sử dụng để kiểm tra kiểu file Đó là: Phương thức Miêu tả stats.isFile() Trả true file stats.isDirectory() Trả true thư mục stats.isBlockDevice() Trả true Block Device stats.isCharacterDevice() Trả true Character Device stats.isSymbolicLink() Trả true Symbolic Link stats.isFIFO() Trả true kiểu FIFO stats.isSocket() Trả true kiểu Socket Ví dụ Sau ví dụ minh họa cách lấy thơng tin file Tạo main.js sử dụng phương thức stat() fs Module trình bày trên: http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     var fs = require("fs"); console.log("Chuan bi lay fs.stat('input.txt', function (err, stats) { if console.error(err); } console.log(stats); File cong!"); // Kiem tra kieu file stats.isFile()); console.log("isDirectory ? " + }); thong tin File hien tai!"); (err) { return console.log("Lay thong tin console.log("isFile ? " + stats.isDirectory()); Chạy main.js để xem kết quả: $ node main.js Kiểm tra kết quả: Chuan bi lay thong tin File hien tai! { dev: 1792, uid: 48, blocks: 8, gid: 48, rdev: 0, blksize: 4096, mode: 33188, ino: 4318127, atime: Sun Mar 22 2015 13:40:00 GMT-0500 (CDT), 22 2015 13:40:57 GMT-0500 (CDT), nlink: 1, size: 97, mtime: Sun Mar ctime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT) } Lay thong tin File cong! isFile ? true isDirectory ? false Ghi liệu vào File Node.js Cú pháp Để ghi liệu vào File Node.js, bạn sử dụng phương thức writeFile() fsModule sau: fs.writeFile(filename, data[, options], callback) Phương thức ghi đè file tồn Chi tiết tham số • path - Đây chuỗi biểu diễn tên file đường dẫn tới file • data - Dữ liệu dạng String Buffer để ghi vào File • options - Tham số đối tượng giữ {encoding, mode, flag} Theo mặc định, mã hóa utf8, mode giá trị 0666 flag 'w' • callback - Hàm callback nhận tham số err sử dụng để trả lỗi xảy lỗi hoạt động ghi Ví dụ Ví dụ sau minh họa cách ghi liệu tới file Tạo main.js có nội dung sau: http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     var fs = require("fs"); console.log("Chuan bi ghi du lieu vao file hien tai"); fs.writeFile('input.txt', 'Hoc Node.js co ban tai VietJack!', function(err) { if (err) { return console.error(err); } console.log("Ghi du lieu vao file cong!"); console.log("Doc du lieu vua duoc ghi"); fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Phuong thuc doc file khong dong bo: " + data.toString()); }); }); Chạy main.js để xem kết quả: $ node main.js Kiểm tra kết quả: Chuan bi ghi du lieu vao file hien tai Ghi du lieu vao file cong! Doc du lieu vua duoc ghi Phuong thuc doc file khong dong bo: Hoc Node.js co ban tai VietJack! Đọc liệu từ File Node.js Cú pháp Để đọc liệu từ File, bạn sử dụng phương thức read() có cú pháp sau: fs.read(fd, buffer, offset, length, position, callback) Phương thức sử dụng tham số fd (viết tắt File Descriptor) để đọc file Nếu bạn muốn đọc file sử dụng trực tiếp tên file bạn nên sử dụng phương thức khác Chi tiết tham số • fd - Là viết tắt file descriptor trả phương thức fs.open() • buffer - Đây Buffer, nơi liệu ghi vào • offset - Đây offset Buffer để liệu bắt đầu ghi từ vị trí • length - Một số nguyên xác định số byte để đọc • position - Một số nguyên xác định nơi bắt đầu đọc từ file Nếu vị trí null, liệu đọc từ vị trí file • callback - Một hàm callback nhận ba tham số, có dạng (err, bytesRead, buffer) http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Ví dụ Tạo main.js có nội dung sau: var fs = require("fs"); var buf = new Buffer(1024); console.log("Chuan bi mo mot File dang ton tai"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File duoc mo cong!"); console.log("Chuan bi doc du lieu tu File da mo"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } console.log(bytes + " bytes read"); // In so luong byte da doc if(bytes > 0){ console.log(buf.slice(0, bytes).toString()); } }); }); Chạy main.js để xem kết quả: $ node main.js Kiểm tra kết quả: Chuan bi mo mot File dang ton tai File duoc mo cong! Chuan bi doc du lieu tu File da mo 97 bytes read VietJack la trang Web huong dan cac bai lap trinh hoan toan mien phi cho tat ca moi nguoi!!!!! Đóng File Node.js Cú pháp Để đóng file sau mở, bạn sử dụng phương thức close() có cú pháp: fs.close(fd, callback) Chi tiết tham số • fd - Là viết tắt file descriptor trả phương thức fs.open() • callback - Hàm callback nhận tham số để xử lý trường hợp có exception Ví dụ Tạo main.js có nội dung: var fs = require("fs"); var buf = new Buffer(1024); console.log("Chuan bi mo mot File dang ton tai"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File duoc mo cong!"); console.log("Chuan bi doc du lieu tu File da mo"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } // In so luong byte da doc if(bytes > 0){ console.log(buf.slice(0, bytes).toString()); } // http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Dong mot File vua duoc mo console.log(err); } cong."); }); }); }); fs.close(fd, function(err){ if (err){ console.log("File duoc dong Chạy main.js để xem kết quả: $ node main.js Kiểm tra kết quả: Chuan bi mo mot File dang ton tai File duoc mo cong! Chuan bi doc du lieu tu File da mo VietJack la trang Web huong dan cac bai lap trinh hoan toan mien phi cho tat ca moi nguoi!!!!! File duoc dong cong Truncate File Node.js Cú pháp Để truncate file mở, bạn sử dụng phương thúc ftruncate() có cú pháp: fs.ftruncate(fd, len, callback) Chi tiết tham số • fd - Là viết tắt file descriptor trả phương thức fs.open() • len - Là độ dài file sau truncate • callback - Hàm callback nhận tham số để xử lý trường hợp có exception Ví dụ Tạo main.js có nội dung sau: var fs = require("fs"); var buf = new Buffer(1024); console.log("Chuan bi mo mot File dang ton tai"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File duoc mo cong!"); console.log("Chuan bi truncate file"); // Truncate mot File da duoc mo fs.ftruncate(fd, 10, function(err){ if (err){ console.log(err); } console.log("File duoc truncate cong."); console.log("Chuan bi doc du lieu tu File"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } // In so luong byte da doc if(bytes > 0){ console.log(buf.slice(0, bytes).toString()); } // Dong File vua mo fs.close(fd, function(err){ if (err){ console.log(err); } console.log("File duoc dong cong."); }); }); }); }); http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Chạy main.js để xem kết quả: $ node main.js Kiểm tra kết quả: Chuan bi mo mot File dang ton tai File duoc mo cong! Chuan bi truncate file File duoc truncate cong Chuan bi doc du lieu tu File VietNamVo File duoc dong cong Xóa File Node.js Cú pháp Để xóa file Node.js, bạn sử dụng phương thức unlink() có cú pháp: fs.unlink(path, callback) Chi tiết tham số • path - Là tên file tên đường dẫn trỏ đến file • callback - Hàm callback nhận tham số để xử lý trường hợp có exception Ví dụ Tạo main.js có nội dung sau: var fs = require("fs"); console.log("Chuan bi xoa mot File dang ton tai"); fs.unlink('input.txt', function(err) { if (err) { return console.error(err); } console.log("Xoa File cong!"); }); Chạy main.js để xem kết quả: $ node main.js Kiểm tra kết quả: Chuan bi xoa mot File dang ton tai Xoa File cong! Tạo thư mục Node.js Cú pháp Để tạo thư mục Node.js, bạn sử dụng phương thức mkdir() có cú pháp: http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     fs.mkdir(path[, mode], callback) Chi tiết tham số • path - Là tên thư mục bao gồm đường dẫn trỏ tới thư mục • mode - Chế độ xác định quyền cho phép truy cập thư mục Giá trị mặc định 0777 • callback - Hàm callback nhận tham số để xử lý trường hợp có exception Ví dụ Tạo main.js có nội dung sau: var fs = require("fs"); console.log("Chuan bi tao thu muc /tmp/test"); fs.mkdir('/tmp/test',function(err){ if (err) { return console.error(err); } console.log("Thu muc duoc tao cong!"); }); Chạy main.js để xem kết quả: $ node main.js Kiểm tra kết quả: Chuan bi tao thu muc /tmp/test Thu muc duoc tao cong! Đọc thư mục Node.js Cú pháp Để đọc thư mục Node.js, bạn sử dụng phương thức readdir() có cú pháp: fs.readdir(path, callback) Chi tiết tham số • path - Là tên thư mục bao gồm đường dẫn trỏ tới thư mục • callback - Hàm callback nhận hai tham số, dạng (err, files) files mảng chứa tên file thư mục Ví dụ Tạo main.js có nội dung sau: http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     var fs = require("fs"); console.log("Chuan bi doc thon tin tu thu muc /tmp"); fs.readdir("/tmp/",function(err, files){ if (err) { return console.error(err); } files.forEach( function (file){ console.log( file ); }); }); Chạy main.js để xem kết quả: $ node main.js Kiểm tra kết quả: Chuan bi doc thon tin tu thu muc /tmp ccmzx99o.out ccyCSbkF.out employee.ser hsperfdata_apache test test.txt Xóa thư mục Node.js Cú pháp Để xóa thư mục Node.js, bạn sử dụng phương thức rmdir() có cú pháp: fs.rmdir(path, callback) Chi tiết tham số • path - Là tên thư mục bao gồm đường dẫn trỏ tới thư mục • callback - Hàm callback nhận tham số để xử lý trường hợp có exception Ví dụ Tạo main.js có nội dung sau: var fs = require("fs"); console.log("Chuan bi xoa thu muc /tmp/test"); fs.rmdir("/tmp/test",function(err){ if (err) { return console.error(err); } console.log("Chuan bi doc thon tin tu thu muc /tmp"); fs.readdir("/tmp/",function(err, files){ if (err) { return console.error(err); } files.forEach( function (file){ console.log( file ); }); }); }); Chạy main.js để xem kết quả: $ node main.js Kiểm tra kết quả: http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/nodejs/index.jsp                                                                                                              Copyright  ©  vietjack.com     Chuan bi doc thon tin tu thu muc /tmp ccmzx99o.out ccyCSbkF.out employee.ser hsperfdata_apache test.txt   http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   ... động Đọc /Ghi file Node.js Flag Miêu tả r Mở file để đọc Xuất Exception file không tồn r+ Mở file để đọc ghi Xuất Exception file không tồn rs Mở file để đọc chế độ đồng rs+ Mở file để đọc ghi, báo... tại, tạo file Giống 'w' hoạt động thất bại file không tồn (tức khơng tạo file mới) Mở file để đọc ghi Nếu file khơng tồn tại, tạo file wx+ Giống 'w+' hoạt động thất bại file không tồn a Mở file để... thong tin File cong! isFile ? true isDirectory ? false Ghi liệu vào File Node.js Cú pháp Để ghi liệu vào File Node.js, bạn sử dụng phương thức writeFile() fsModule sau: fs.writeFile(filename,

- Xem thêm -

Xem thêm: doc ghi file trong nodejs,