文件的Javascript自动化移动到另一个文件夹中 [英] Javascript automation for files move into another folder

查看:689
本文介绍了文件的Javascript自动化移动到另一个文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器中有一个包含一些文件的文件夹。这些都是自动化的,这意味着我们每天都会自动获取新文件,覆盖旧文件。所以想要为这些数据进行备份。我怎么能复制所有这些文件到另一个文件夹通过重命名复制当前日期的文件。

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.

例如:我有一个名为folder1的文件夹,其中包含4个文件。此文件夹的路径是 home / webapps / project1 / folder1

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



<现在我想将所有这四个文件复制到另一个名为 folder2 的文件夹中。此文件夹的路径是 home / webapps / project1 / folder2 。在复制这些文件时,我想重命名每个文件并将当前日期添加到文件中。所以我在 folder2 中的文件名应该是..

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

我想用Javascript编写一个脚本。请给我一些想法或者与此相关的一些示例脚本。 $ b

I want to write a script for this using Javascript. Please give me some idea or some sample scripts related to this.

推荐答案


$ b

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")

您可以使用此npm lib: https://github.com/ncb000gt/node-cron ,做一些工作提名。

You can use this npm lib: https://github.com/ncb000gt/node-cron, to do some job autominate.

这篇关于文件的Javascript自动化移动到另一个文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆