fs.createReadStream
时间: 2023-09-10 20:13:13 浏览: 47
fs.createReadStream is a method in Node.js that creates a readable stream from a file path or file descriptor. It returns an instance of the ReadStream class, which can be used to read data from a file in chunks.
The syntax for fs.createReadStream is as follows:
```
fs.createReadStream(path[, options])
```
Here, `path` is the path to the file to be read, and `options` is an optional object that can be used to configure the stream. Some of the common options include:
- `flags`: Specifies the file system flags that should be used when opening the file. The default value is 'r', which opens the file for reading.
- `encoding`: Specifies the encoding to be used when reading the file. The default is null, which means that the data will be returned as raw bytes.
- `highWaterMark`: Specifies the maximum number of bytes to be read at a time. The default is 64KB.
Once the ReadStream instance is created, it can be used to read data from the file using the `read()` method. Data is read in chunks and emitted as `data` events. When all the data has been read, a `end` event is emitted.
Here's an example usage of fs.createReadStream:
```
const fs = require('fs');
const path = 'example.txt';
const stream = fs.createReadStream(path, { encoding: 'utf8' });
stream.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
stream.on('end', () => {
console.log('Finished reading the file.');
});
stream.on('error', (err) => {
console.error(err);
});
```
This code creates a ReadStream that reads the contents of the file 'example.txt' as UTF-8 encoded text. As data is read from the file, the `data` event is emitted with a chunk of data. Once all the data has been read, the `end` event is emitted. If an error occurs while reading the file, the `error` event is emitted with the error object.