Talker Talker - 1 year ago 41
Node.js Question

How to use promises in NodeJs while processing files in the case below

I learn Javascript and I need some help with promises.

I have a code:

'use strict';

const fs = require('mz/fs');

.then(function(filesNames) {
return Promise.all( => fs.stat(fileName))
}) /*** after this, the file names are lost ***/
.then(function(stats) {
return stats.filter(stat => stat.isFile())
.then(function(stats) {
return stats.reduce((sum, stat) => sum + stat.size, 0)

It calculates the total length of all files in a folder. The question is - what if I also need to read the files content? But after the first ".then()" file names are lost...

In short I need:

  1. Read the list of files in a folder

  2. Check the list and throw away folder names from it

  3. Read each file in the list

Could you explain me how to do this?

Answer Source

It is the job of the function that return the stat to also return the filenames: => {
    return fs.stat(fileName).then(stat => {
        return {name: fileName, stat: stat};