fs.readFile(path[, options], callback)
參數解析:
path <string> | <Buffer> | <URL> | <integer> 文件名或文件描述符。
options <Object> | <string>
encoding <string> | <null> 默認值: null。
flag <string> 參閱支持的文件系統標誌。默認值: 'r'。
callback <Function>
err <Error>
data <string> | <Buffer>
異步地讀取文件的全部內容。
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
回調會傳入兩個參數 (err, data),其中 data 是文件的內容。
如果沒有指定 encoding,則返回原始的 buffer。
如果 options 是字符串,則它指定字符編碼:
fs.readFile('/etc/passwd', 'utf8', callback);
當 path 是目錄時, fs.readFile() 與 fs.readFileSync() 的行爲是特定於平臺的。 在 macOS、Linux 和 Windows 上,將返回錯誤。 在 FreeBSD 上,將返回目錄內容的表示。
// 在 macOS、Linux 和 Windows 上:
fs.readFile('<目錄>', (err, data) => {
// => [Error: EISDIR: illegal operation on a directory, read <目錄>]
});
// 在 FreeBSD 上:
fs.readFile('<目錄>', (err, data) => {
// => null, <data>
});
fs.readFile() 函數會緩衝整個文件。 爲了最小化內存成本,儘可能通過 fs.createReadStream() 進行流式傳輸。
fs.readFileSync(path[, options])
默認返回的是buffer