2

I have a synchronous process I am migrating from C# to nodejs which checks a directory daily for certain files. If those files exist it adds them to a TAR file and writes that TAR to a different directory. Whilst checking for any relevant files using a forEach loop, I am struggling to get my process to wait for the loop to complete before moving onto the next function, to create the TAR file.

I have tried using the async module as suggested here and promises as suggested here. Without much success.

By making use of the async module I am hoping to halt the execution of commands so that my loop may finish before the fileList array is returned. As it currently stands, I am receiving a TypeError: Cannot read property 'undefined' of undefined.

My question: will async halt execution until my loop completes, if so what am I doing wrong?

Thanks for looking, please see my code below.

var fs = require('fs'), // access the file system.
    tar = require('tar'), // archiving tools.
    async = require('async'), // async tool to wait for the process's loop to finish.
    moment = require('moment'), // date / time tools.
    source = process.env.envA, // environment variable defining the source directory.
    destination = process.env.envB, // environment variable defining the destination directory.
    archiveName = process.env.envArc, // environment variable defining the static part of the TAR file's name.
    searchParameter = process.env.env1, // environment variable defining a file search parameter.
    date = moment().format('YYYYMMDD'); // Create a date object for file date comparison and the archive file name.

// Change working directory the process is running in.
process.chdir(source);

// Read the files within that directory.
fs.readdir(source, function (err, files) {
    // If there is an error display that error.
    if (err) {
        console.log('>>> File System Error: ' + err);
    }

    // **** LOOP ENTRY POINT ****
    // Loop through each file that is found,
    // check it matches the search parameter and current date e.g. today's date.
    CheckFiles(files, function (fileList) {
        // If files are present create a new TAR file...
        if (fileList > 0) {
            console.log('>>> File detected. Starting archiveFiles process.');
            archiveFiles(fileList);
        } else { // ...else exit the application.
            console.log('>>> No file detected, terminating process.');
            //process.exit(0);
        }
    });
});

var CheckFiles = function (files, callback) {
    console.log('>>> CheckFiles process starting.');

    var fileList = []; // Create an empty array to hold relevant file names.

    // **** THE LOOP IN QUESTION **** 
    // Loop through each file in the source directory...
    async.series(files.forEach(function (item) {
        // ...if the current file's name matches the search parameter...
        if (item.match(searchParameter)) {
            // ...and it's modified property is equal to today...
            fs.stat(item, function (err, stats) {
                if (err) {
                    console.log('>>> File Attributes Error: ' + err);
                }
                var fileDate = moment(stats.mtime).format('YYYYMMDD');

                if (fileDate === date) {
                    // ...add to an array of file names.
                    fileList.push(item);
                    console.log('>>> Date match successful: ' + item);
                } else {
                    console.log('>>> Date match not successful:' + item);
                }
            });
        }
    }), callback(fileList)); // Once all the files have been examined, return the list of relevant files.
    // **** END LOOP ****

    console.log('>>> CheckFiles process finished.');
};

var archiveFiles = function (fileList) {
    console.log('>>> Starting archiveFiles process.');

    if (fileList.length > 0) {
        // Tar the files in the array to another directory.
        tar.c({}, [fileList[0], fileList[1]]).pipe(fs.createWriteStream(destination + archiveName));
        // TODO Slack notification.
        console.log('>>> TAR file written.');
    }
};
mepilp
  • 97
  • 2
  • 12
  • What about a `Promise`? https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise – Lucas Jun 12 '17 at 13:55
  • Hi @I'm Blue Da Ba Dee I've been refactoring the code to use promises as you've suggested, but as @Cheloide points out: due to the async nature of `fs.stat` I haven't quite fixed it yet. – mepilp Jun 14 '17 at 07:43

2 Answers2

3

Async was unnecessary, the use of Promises as suggested by @I'm Blue Da Ba Dee and fs.statSync as suggested by @Cheloid fulfilled my requirements. For anyone that may benefit from this outcome, please see my code below.

var fs = require('fs'), // access the file system.
    tar = require('tar'), // archiving tools.
    moment = require('moment'),  // date / time tools.
    source = process.env.envA, // environment variable defining the source directory.
    destination = process.env.envB, // environment variable defining the destination directory.
    archiveName = process.env.envArc, // environment variable defining the static part of the TAR file's name.
    searchParameter = process.env.env1, // environment variable defining a file search parameter.
    date = moment().format('YYYYMMDD'), // create a date object for file date comparison and the archive file name.
    fileList = [], // create an empty array to hold relevant file names.
    slack = require('./slack.js'); // import Slack notification functionality.

// Change working directory the process is running in.   
process.chdir(source);

// Read the files within that directory.
fs.readdir(source, function (err, files) {
    // If there is an error display that error.
    if (err) console.log('>>> File System Error: ' + err);

    // Loop through each file that is found...
    checkFilesPromise(files).then(function (response) {
        console.log('>>> File(s) detected. Starting archiveFilesPromise.');

        // Archive any relevant files.
        archiveFilesPromise(fileList).then(function (response) {
            console.log('>>> TAR file written.');

            // Send a Slack notification when complete.
            slack('TAR file written.', 'good', response);
        }, function (error) {
            console.log('>>> archiveFilesPromise error: ' + error);
            slack('archiveFilesPromise error:' + error, 'Warning', error);
        });
    }, function (error) {
        console.log('>>> CheckFilesPromise error ' + error);
        slack('CheckFilesPromise error: ' + error, 'Warning', error);
    });
});

var checkFilesPromise = function (files) {
    return new Promise(function (resolve, reject) {
        files.forEach(function (item) {
            // ...check it matches the search parameter...
            if (item.match(searchParameter)) {
                var stats = fs.statSync(item);
                var fileDate = moment(stats.mtime).format('YYYYMMDD');

                // ...and current date e.g. today's date.
                if (fileDate === date) {
                    // Add file to an array of file names.
                    console.log('>>> Date match successful, pushing: ' + item);
                    fileList.push(item);
                    resolve('Success');
                 } else {
                    reject('Failure');
                }
            }
        });
    });
};

var archiveFilesPromise = function (list) {
    return new Promise(function (resolve, reject) {

        if (list.length > 0) {
            // Tar the files in the array to another directory.
            tar.c({}, [list[0], list[1]]).pipe(fs.createWriteStream(destination + date + archiveName));
            resolve('Success');
        } else {
            reject('Failure');
        }
    });
};
mepilp
  • 97
  • 2
  • 12
0

You could use a normal for loop and at the last iteration call the callback function.

var CheckFiles = function (files, callback) {
    console.log('>>> CheckFiles process starting.');

    var fileList = []; // Create an empty array to hold relevant file names.
    for (var i = 0, n = files.length; i < n; ++i)
        // ...if the current file's name matches the search parameter...
        if (item.match(searchParameter)) {
            // ...and it's modified property is equal to today...
            fs.stat(item, function (err, stats) {
                if (err) {
                    console.log('>>> File Attributes Error: ' + err);
                }
                var fileDate = moment(stats.mtime).format('YYYYMMDD');

                if (fileDate === date) {
                    // ...add to an array of file names.
                    fileList.push(item);
                    console.log('>>> Date match successful: ' + item);
                } else {
                    console.log('>>> Date match not successful:' + item);
                }
            });
        }
    if (i === n + 1) {
        callback(fileList);
        console.log('>>> CheckFiles process finished.');
    }
};

Edit:

Use recursive callbacks, I'm not sure if this code will work but I hope you get the idea.

fs.stats is async and therefore the loop does not wait for it... you can use call backs to "wait" for it.

var CheckFiles = function (files, callback) {
    console.log('>>> CheckFiles process starting.');

    var arrIndex = 0;
    var fileList = [];

    recursiveCallback(fileList, callback); //callling our callback

    function recursiveCallback(array, callback) { //recursive callback inside our function

        var item = files[arrIndex++];

        if (item.match(searchParameter)) {
            // ...and it's modified property is equal to today...
            fs.stat(item, function (err, stats) {
                if (err) {
                    console.log('>>> File Attributes Error: ' + err);
                }
                var fileDate = moment(stats.mtime).format('YYYYMMDD');

                if (fileDate === date) {
                    // ...add to an array of file names.
                    array.push(item);
                    console.log('>>> Date match successful: ' + item);
                } else {
                    console.log('>>> Date match not successful:' + item);
                }
                if (files.length < arrIndex) //when last item, use the main callback to retrieve the array
                    callback(array);
                else    //when not last item , recursion
                    recursiveCallback(item, array, callback);
            });
        } else if (files.length < arrIndex) //when last item, use the main callback to retrieve the array
            callback(array);
        else    //when not last item , recursion
            recursiveCallback(item, array, callback);
    }
}
Cheloide
  • 793
  • 6
  • 21
  • Hi @Cheloide, thanks for your answer. I've tried your suggestion and re-worked it several times. However what I'm finding is that the `fileList.push` operation is executing after the loop has moved on and executed the callback. Either that or my `fileList.push` isn't working at all? – mepilp Jun 13 '17 at 07:56
  • @MattLindsay , I changed my answer. due to the async nature of fs.stats, my last answer will never work (maybe the sync version of fs.stats will work). I haven't had time today otherwise I would replied sooner, I hope it helps. – Cheloide Jun 13 '17 at 21:41
  • Hi @Cheloid , thanks for revising I'm a little closer now. I am finding that the process drops out at the `array.push(item)`. To alleviate this I added `array = []` straight after the `recursiveCallback` constructor which allowed all the relevant files to be selected. Now the process drops out on the last pass where there is effectively no file name. I've tried adding a condition in front of the regex match `if` statement: `typeof item !== undefined`, but that hasn't worked either. Any ideas greatly received. – mepilp Jun 16 '17 at 11:07
  • Tried `if( item )`? – Cheloide Jun 16 '17 at 13:32