核心 API
const fs = require('fs');
const fileContent = fs.readFileSync('/path/to/file', 'utf8');
console.log(fileContent);
說明
fs.readFileSync(path, encoding):同步阻塞讀取,返回字串(指定編碼)或 Buffer(不指定編碼)
- 適合啟動階段載入配置檔、模板等小檔案
- 高併發服務中請改用
fs.readFile(非阻塞)或 fs.createReadStream(流式)
非阻塞版本
fs.readFile('/path/to/file', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
流式讀取大檔案
const stream = fs.createReadStream('/path/to/large.file', {encoding: 'utf8'});
let data = '';
stream.on('data', chunk => data += chunk);
stream.on('end', () => console.log(data));
stream.on('error', err => console.error(err));