Created
March 21, 2013 16:01
-
-
Save h2non/5214201 to your computer and use it in GitHub Desktop.
Simple Node.js recursivily copy/rename files with specific pattern
This file contains hidden or 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
/** | |
* Simple Node.js recursivily copy/rename files with specific pattern | |
* @license WTFPL | |
* @usage $ node copyFiles.js | |
*/ | |
var fs = require('fs'), | |
config; | |
// config options | |
config = { | |
targetDir: '/var/www/static/tmpl', | |
removeFiles: true, | |
matchPattern: /^[_](.*)/gi, | |
replacePattern: '$1', | |
files: [ | |
'_mytmpl.html', | |
'_mytmpl2.html' | |
] | |
}; | |
function walk(dir, done) { | |
var results = []; | |
fs.readdir(dir, function(err, list) { | |
if (err) return done(err); | |
var i = 0; | |
(function next() { | |
var file = list[i++]; | |
if (!file) return done(null, results); | |
file = dir + '/' + file; | |
fs.stat(file, function(err, stat) { | |
if (stat && stat.isDirectory()) { | |
walk(file, function(err, res) { | |
results = results.concat(res); | |
next(); | |
}); | |
} else { | |
results.push(file); | |
next(); | |
} | |
}); | |
})(); | |
}); | |
} | |
function copyFileSync(srcFile, destFile, encoding) { | |
var content = fs.readFileSync(srcFile, encoding || 'utf8'); | |
fs.writeFileSync(destFile, content, encoding || 'utf8'); | |
} | |
function removeFile(srcFile) { | |
fs.unlinkSync(srcFile, function (err) { | |
if (err) throw err; | |
console.log('Successfully deleted: ' + srcFile); | |
}); | |
} | |
// walk the directory recursively | |
walk(config.targetDir, function(err, results) { | |
if (err) throw err; | |
var matchedFiles = []; | |
results.forEach(function(file, i){ | |
var outputFile, | |
targetFile = file.split('/').slice(-1)[0]; | |
if (config.files && config.files.indexOf(targetFile) !== -1) { | |
// store it | |
matchedFiles.push(file); | |
outputFile = targetFile.replace(config.matchPattern, config.replacePattern); | |
console.log('File matched: ' + targetFile); | |
copyFileSync(file, file.replace(targetFile, outputFile)); | |
} | |
}); | |
if (config.removeFiles) { | |
console.log('\n----------------------------------------\n'); | |
matchedFiles.forEach(removeFile); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome code!! Saved my life