Node(10) File System, IO, Stream

Like Http, IO is non-blocking, It is also very commonly used, not as often as Http, but still good to know its funtionality.

readFile/readFileSync

fs.readFile(filename, [encoding], [callback])

The callback is passed two arguments (err, data), where data is the contents of the file.

fs.readFileSync(filename, [encoding])

return the content of the file, no callback needed.



Both of them reads a file, readFileSync read at once and readFile use asynchronous reading, so it has callback functions.
var fs = require('fs');
var filehandle = fs.readFile('data.txt', function(err, data) {
  if(err)throw err;
  console.log(data);
});
output


By default, readFile reads Buffer, to read in utf-8 format:
fs.readFile( 'data.txt', 'utf-8', function(err, data) {...}

fs.stat(path, [callback])

fs.statSync(path)

return a fs.Stats object that contains the information about the file
fs.Stats contains the methods and data about the file like last modified, size etc



fs.createReadStream(path, [options])

return a new Readable Stream object, Readable Stream and Writable Stream are inside the Stream module
Readable Stream object have the following events and methods
data - emits a Buffer or string( if encoding is set )
end - receive EOF
error
close - resource is closed

methods - pause(), resume(), 
pipe(destination, [options]) - pipes a readable stream to a writable stream



Buffer

creating buffer

new Buffer( 10 ) 
- create a buffer of size 10, uninitialized, this is the most common way of creating buffer

buffer class have many methods to read and write to a buffer

property: length
method: [] operator - to get the bite in the index
write - write the string to the buffer








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值