tristantzara
tristantzara

Reputation: 5897

Node async waterfall callback was already called

I'm trying to read some files from dir with async.waterfall, it seems to me that I'm doing stuff right, but I get the specified error and the readData function is never called. What's wrong?

var fs = require("fs");
var async = require("async");

var folder = "./files/";

try {
    async.waterfall([
        function readDir(cb) {
            fs.readdir(folder, function(err, files) {
                cb(err, files);
            });
        },
        function loopFiles(files, cb) {
            files.forEach(function(fn) {
                console.log("loop " + fn);
                cb(null, fn);
            });
        },
        function check(fn, cb) {
            console.log("check "+fn);
            fs.stat(folder + fn, function(err, stats) {
                console.log(stats.isFile());
                cb(err, stats, fn);
            });
        },
        function readData(stats, fn, cb) {
            console.log("read "+fn);
            if (stats.isFile()) {
                fs.readFile(folder + fn, "utf-8", function(err, data) {
                    cb(err, data);
                });
            }
        }
    ], function(err, result) {
        if (err) {
            throw err;
        }
       console.log(result);
    });
} catch (err) {
console.log(err);
}

Upvotes: 2

Views: 3312

Answers (1)

mscdex
mscdex

Reputation: 106698

The problem is that you're calling cb(null, fn) in loopFiles() multiple times if files.length > 1. You will probably need to perform a separate async.waterfall() or use some other async.* method for each file.

One other problem is in readData() where you aren't calling cb() in the case that stats.isFile() evaluates to false.

Upvotes: 3

Related Questions