nodeJS 自学之路 《fs 系统》第一篇:readFileSync 与 readFile

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  

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值