问题
I have a folder in my server which contains some files. These are automated that means everyday we get new files automatically which will overwrite the old ones. So want to take a back up for this data. How can i copy all these files in to a another folder by renaming the files with current date while copying.
Ex : I have a folder named folder1 which contains 4 files. Path for this folder is home/webapps/project1/folder1
aaa.csv
bbb.csv
ccc.csv
ddd.csv
Now I want to copy all these four files in to a different folder named folder2
. Path for this folder is home/webapps/project1/folder2
. While copying these files I want to rename each file and add the current date to the file. So my file names in folder2
should be..
aaa091012.csv
bbb091012.csv
ccc091012.csv
ddd091012.csv
I want to write a script for this using Javascript. Please give me some idea or some sample scripts related to this.
回答1:
You can try this code:
var fs = require('fs');
var path = require('path');
function dateFormat(){
var date = new Date();
var year = (date.getFullYear() + '').slice(2);
var month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
return year+month+day;
}
function moveAndRename(sourceDir, destDir){
fs.readdir(sourceDir, function(err, files){
if(err)
return err;
else {
files.forEach(function(file){
var dotIndex = file.lastIndexOf(".");
var name = file.slice(0, dotIndex);
var newName = (name + dateFormat()) + path.extname(file);
var read = fs.createReadStream(path.join(sourceDir, file));
var write = fs.createWriteStream(path.join(destDir, newName));
read.pipe(write);
});
}
});
}
moveAndRename("/home/webapps/project1/folder1",
"/home/webapps/project1/folder2")
You can use this npm lib: https://github.com/ncb000gt/node-cron, to do some job autominate.
来源:https://stackoverflow.com/questions/29404104/javascript-automation-for-files-move-into-another-folder