Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Parallel in node.js (example with async and co https://github.com/visionmedia/co)
#!/usr/bin/env node
var fs = require('fs');
var async = require('async');
async.parallel([
copyFile.bind(null, 'resources/file1.txt', 'resources/file1_copy.txt'),
copyFile.bind(null, 'resources/file2.txt', 'resources/file2_copy.txt'),
copyFile.bind(null, 'resources/file3.txt', 'resources/file3_copy.txt')
], function (err, results) {
if(err) {
console.error('There was an error copying files', err);
throw err;
}
console.log('copied %d files', results.length);
})
function copyFile (source, dest, callback) {
fs.createReadStream(source)
.on('error', callback)
.pipe(fs.createWriteStream(dest))
.on('error', callback)
.on('finish', callback)
}
#!/usr/bin/env node
var fs = require('fs');
var co = require('co');
var thunkify = require('thunkify');
var copy = thunkify(copyFile);
co(function *() {
var a = copy('resources/file1.txt', 'resources/file1_copy.txt');
var b = copy('resources/file2.txt', 'resources/file2_copy.txt');
var c = copy('resources/file3.txt', 'resources/file3_copy.txt');
var results = yield [a, b , c];
console.log('copied files', results);
})()
function copyFile (source, dest, callback) {
fs.createReadStream(source)
.on('error', callback)
.pipe(fs.createWriteStream(dest))
.on('error', callback)
.on('finish', callback)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.