Created
June 3, 2013 15:04
-
-
Save magalhini/5698840 to your computer and use it in GitHub Desktop.
Concatenate files with node.js
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
/* USAGE: | |
node fjoin file1 file2 file 3 | |
or | |
fjoin({files, target}) | |
*/ | |
var util = require('util'), | |
fs = require('fs'), | |
files = [], | |
readstream, | |
i = 1; | |
var streamFile = function (stream) { | |
var file = files.shift(); | |
readstream = fs.createReadStream(file, {encoding: 'utf-8'}); | |
readstream.on('end', function () { | |
if (files.length) { | |
streamFile(stream); | |
i += 1; | |
} else { | |
stream.end(); | |
console.log('All done,', i, 'files joined.'); | |
} | |
}); | |
readstream.pipe(stream, { end: false }); | |
}; | |
var fjoin = function (options, config) { | |
var newFile = fs.createWriteStream(options.target), | |
args = process.argv.slice(2, process.argv.length); | |
files = args.length ? args : options.files.slice(0); | |
if (files.length) streamFile(newFile); | |
}; | |
fjoin({ | |
files: ['text.txt', 'text.txt'], | |
target: 'final.txt' | |
}); | |
exports.fjoin = fjoin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment