Search code examples
javascriptnode.jsasynchronousfssynchronous

Read files in series with fs.readFile in Node?


I have an arbitrary number file paths stored in an array as strings.

I need to read these files in series (i.e. finish reading one file before starting reading the next one), and output the file length after each file read. And after finish reading all files, print 'done'.

I'm only allowed to use fs.readFile and native Javascript. No fs.readFileSync or any other module is allowed. Also, I'm on Node v6, so I can't use async/await.

Is there any way to implement the functionality, following the constraints?


Solution

  • You don't need any fancy stuff like promises, async/await, generators to achieve that.

    function readAllFiles(list) {
      if(list.length == 0) return
      console.log('reading ', list[0])
      return fs.readFile(list[0], function (err, file) {
        if (err) console.error(err); // report the error and continue
        console.log('list[0] length:', file.length); // report the file length
        readAllFiles(list.slice(1, list.length))
      })
    }
    
    var l = ['1', 'foo', 'bar']
    
    readAllFiles(l)