Suppose I have a directory that contains 100K+ or even 500k+ files. I want to read the directory with fs.readdir
, but it's async not stream. Someone tell me that async use memory before done read the entire file list.
So what is the solution? I want to readdir with stream approach. Can I?
The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.
createReadStream() Method. The createReadStream() method is an inbuilt application programming interface of fs module which allow you to open up a file/stream and read the data present in it.
Filestream in Node. js. Node makes extensive use of streams as a data transfer mechanism. For example, when you output anything to the console using the console. log function, you are actually using a stream to send the data to the console.
Now there is a way to do it with async iteration! You can do:
const dir = fs.opendirSync('/tmp')
for await (let file of dir) {
console.log(file.name)
}
To turn it into a stream:
const _pipeline = util.promisify(pipeline)
await _pipeline([
Readable.from(dir),
... // consume!
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With