Parallel in node.js (example with async and co https://github.com/visionmedia/co)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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