Instructions for the fs.createReadStream method in node.js

  • 2020-05-07 19:12:46
  • OfStack

method description:

Returns an readStream (file read stream, input stream) object. (readable stream)

syntax:


fs.createReadStream(path, [options])

Since this method belongs to the fs module, the fs module (var fs= require(" fs ")) needs to be introduced before use.

receive parameter:

path: (string) the path to the file to be read

The options: (object) array object contains the following properties


{ flags: 'r',
  encoding: null,
  fd: null,
  mode: 0666,
  autoClose: true
}

Instead of reading the entire file, options can set the range of bytes that can be read by start and end.

If both start and end are included, it will start at 0.

encodeing can be 'utf8 ',' ascii', or 'base64'.

If autoClose is false, the file descriptors will not be closed, even if they report an error.

It is best to close it and ensure that no file descriptor leaks occur.

If autoClose is true (the default behavior), the file descriptor for errors or ends is automatically closed.

example:

This example will read the last 1010 bytes in a 100k file.


fs.createReadStream('sample.txt', {start: 90, end: 99});

source code:


fs.createReadStream = function(path, options) {
  return new ReadStream(path, options);
};


Related articles: