Skip to content

Instantly share code, notes, and snippets.

@seanhess
Created November 17, 2011 00:41
Show Gist options
  • Save seanhess/1372013 to your computer and use it in GitHub Desktop.
Save seanhess/1372013 to your computer and use it in GitHub Desktop.
Examples
var path = require('path')
var fs = require('fs')
// FS EXAMPLE - concat all js files in dir and save to destFile
// This is normal node.js code
function concatJsFiles(dir, destFile, cb) {
fs.readdir(dir, function(err, files) {
if (err) return cb(err)
// Filter *.js files
files = files.filter(function (name) {
return (name.slice(-3) === '.js');
});
// Read all the files (in a parallel loop)
var fileContents = []
function getContentsOfAllFiles(cb) {
files.forEach(function(file) {
var fullPath = path.join(dir, file)
fs.readFile(fullPath, 'utf-8', function(err, contents) {
if (err) return cb(err)
fileContents.push(contents)
if (fileContents.length == files.length)
cb(null, fileContents)
})
})
}
getContentsOfAllFiles(function(err, contents) {
if (err) return cb(err)
// Join them all together
var combined = contents.join("\n")
// Save them
fs.writeFile(destFile, combined, 0775, function(err) {
cb(err, files) // so we know which files we included
})
})
})
}
var fromPromises = require('theframework')
var path = require('path')
var fs = require('fs')
// concatJsFiles = function(dir, destFile, cb)
var concatJsFiles = fromPromises(fs, path, function(fs, path, dir, destFile) {
var files = fs.readdir(dir)
// filter *.js files
files = files.filter(function (name) {
return (name.slice(-3) === '.js');
});
// same as "getContentsOfAllFiles" step above.
// Note that this contains an async operation
var contents = files.map(function(file) {
var fullPath = path.join(dir, file)
return fs.readFile(fullPath, 'utf-8')
})
// combine into one file
var combined = contents.join("\n")
// write the file
fs.writeFile(destFile, combined, 0775)
// sends return value to 2nd param: cb(err, files)
return files
})
var fromPromises = require('theframework')
var path = require('path')
var fs = require('fs')
// You can chain things
var concatJsFiles = fromPromises(fs, path, function(fs, path, dir, destFile) {
var combined = fs
.readdir(dir)
.filter(function (name) {
return (name.slice(-3) === '.js');
})
.map(function(file) {
var fullPath = path.join(dir, file)
return fs.readFile(fullPath, 'utf-8')
})
.join("\n")
fs.writeFile(destFile, combined, 0775)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment