Skip to content

Instantly share code, notes, and snippets.

@magalhini
Created June 3, 2013 15:04
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 magalhini/5698840 to your computer and use it in GitHub Desktop.
Save magalhini/5698840 to your computer and use it in GitHub Desktop.
Concatenate files with node.js
/* 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