Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created August 13, 2016 23:43
Show Gist options
  • Save miguelmota/3726b0ad59ef5854f852dff1449e3bf2 to your computer and use it in GitHub Desktop.
Save miguelmota/3726b0ad59ef5854f852dff1449e3bf2 to your computer and use it in GitHub Desktop.
Node.js concat files in directory
var fs = require('fs');
var dirname = '/some-dir/';
function onFileContent(filename, content) {
if (!/\.(js|md|txt)$/.test(filename)) {
return false;
}
var str = filename + '\n\n' + content + '\n\n\n\n\n';
console.log(str);
}
function onError(error) {
console.log(error);
}
readFiles(dirname, onFileContent, onError);
function readFiles(dirname, onFileContent, onError) {
fs.readdir(dirname, function(err, filenames) {
if (err) {
onError(err);
return;
}
filenames.forEach(function(filename) {
fs.readFile(dirname + filename, 'utf-8', function(err, content) {
if (err) {
onError(err);
return;
}
onFileContent(filename, content);
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment