Skip to content

Instantly share code, notes, and snippets.

@nguyentien98
Last active November 1, 2018 03:49
Show Gist options
  • Save nguyentien98/c07f22fabe6338efe0f0d5e9d9076fa5 to your computer and use it in GitHub Desktop.
Save nguyentien98/c07f22fabe6338efe0f0d5e9d9076fa5 to your computer and use it in GitHub Desktop.

File system trong nodejs

Để khai báo ta dùng:

const fs = require('fs');

Môt số hàm ta có thể dùng: Hàm readFile: đọc nội dung file. Hàm này cần callback để có thể lấy nội dung file.

fs.readFile('path-to-file', function (err, data) {
});

Hàm readFileSync: cũng có tác dụng đọc file. Tuy nhiên nó là hàm đồng bộ (sync), không cần callback để xử lý dữ liệu.

let content = fs.readFileSync('path-to-file', 'utf-8');

Hàm appendFile, có tác dụng append 1 nội dung vào file.

fs.appendFile(filePath, content, (err) => {
});
 

Hàm rename, đổi tên file

fs.rename('path', 'new-path', function (err){});

Hàm unlink: xóa file

fs.unlink('path', function (err) {});

Hàm unlinkSync: xóa file đồng bộ

fs.unlink('path');

Hàm createReadStream: tạo ra 1 stream read file khi có sự thay đổi ở file. Sau đó ta có thể bind vào response của server bằng cách dùng .pipe(res). res là 1 instance của ServerResponse.

fs.createReadStream('./index.html').pipe(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment