Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stream read directory in node.js?

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?

like image 904
raitucarp Avatar asked Sep 10 '14 04:09

raitucarp


People also ask

How do I read a folder in node JS?

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.

How do I create a read stream in node?

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.

What is Filestream in NodeJS?

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.


1 Answers

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!
])

like image 94
Kirill Groshkov Avatar answered Oct 25 '22 03:10

Kirill Groshkov