Skip to content

Instantly share code, notes, and snippets.

@Floby
Created August 29, 2014 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Floby/cfef7f29d6493436ff92 to your computer and use it in GitHub Desktop.
Save Floby/cfef7f29d6493436ff92 to your computer and use it in GitHub Desktop.
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