Skip to content

Instantly share code, notes, and snippets.

@h2non
Created March 21, 2013 16:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save h2non/5214201 to your computer and use it in GitHub Desktop.
Save h2non/5214201 to your computer and use it in GitHub Desktop.
Simple Node.js recursivily copy/rename files with specific pattern
/**
* 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);
}
});
@luispied
Copy link

Awesome code!! Saved my life

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment