Scenario
Need to run two tasks in parallel, and run the third task after firstTask && secondTask
are done. Have been using async
library and the code works, but want to know if there is something I could improve about my code.
Details
Task 1: readFileNames
: reads a folder and returns an array of file names.
Task 2: copyFile
: copy a config
file from src folder to a destination folder.
Task 3: writeConfig
: write the result of readFileNames
into the config
file located at the destination
folder.
Questions
Should I combine the parallel
control flow with eachSync
? Also, was wondering if promises would help me achieve what I am trying to do? And which approach is better in terms of performance? Async vs Q or should I use a more abstracted library like orchestrator
?
Below is what I have so far, it works but was wondering if there is a better way of doing it:
Code
var async = require("async");
var fs = require("fs-extra");
var dir = require("node-dir");
var path = require("path");
var _ = require("underscore");
var readFileNames = function (src, cb) {
dir.files(src, function (err, files) {
if (err) { return cb(err); }
return cb(files);
});
};
var copyFile = function (src, dest, cb) {
fs.copy(src, dest, function (err) {
if (err) { return cb(err); }
return cb();
});
};
var writeConfig = function (destFile, content, cb) {
fs.appendFile(destFile, content, function (err) {
if (err) { return cb(err); }
return cb();
});
};
var modulesFolder = path.join(__dirname, "modules");
var srcFile = path.join(__dirname, "src", "config.json");
var destFile = path.join(__dirname, "dest", "config.json");
async.parallel(
[
function (callback) {
readFileNames(modulesFolder, function (files) {
callback(null, files);
});
},
function (callback) {
copyFile(srcFile, destFile, function () {
callback(null, "");
});
}
],
// last callback
function (err, results) {
var toWrite = _.flatten(results);
toWrite.forEach(function (content) {
if(content) {
writeConfig(destFile, content + "\n", function () {
});
}
});
console.log("done");
}
);
files
├── dest
├── main.js
├── modules
│ ├── module1.txt
│ └── module2.txt
├── node_modules
│ ├── async
│ ├── fs-extra
│ └── node-dir
├── package.json
└── src
└── config.json