Nodejs实现多文件夹文件同步

2018-10-17 16 迦蓝叶

本文实例为大家分享了Nodejs实现多文件夹文件同步的具体代码,供大家参考,具体内容如下

package.json

{
 "name": "asyncFile",
 "version": "0.0.1",
 "dependencies":{
 "fs-sync":"",
 "later":""
 }
}

asycnFile.js

var fsSync = require('fs-sync');
var fs = require('fs');
var util = require("util");
var later = require("later");

//需要同步的文件夹路径
var path = {
 "pathOne": "/home/lincoln/testAsync/dirOne/",
 "pathTwo": "/home/lincoln/testAsync/dirTwo/"
};

//需要同步的文件夹名称
var asyncDir = ["img", "music"];

var dirFilesOne;
var dirFilesTwo;

//读取文件夹信息
function readDir(dirName){
 dirFilesOne = fs.readdirSync(path.pathOne + dirName);
 dirFilesTwo = fs.readdirSync(path.pathTwo + dirName);
}

//使用fs-sync模块拷贝文件信息
function useFileCopy(sourcePath,distPath,copyFiles) {
 for(var index in copyFiles){
  fsSync.copy(sourcePath+copyFiles[index],distPath+copyFiles[index])
 }
}

//统计需要同步的文件信息
function needCopyFiles(sourceFiles, distFiles) {
 var needCopyFiles = [];
 for (var index in sourceFiles) {
  if (distFiles.indexOf(sourceFiles[index]) == -1) {
   needCopyFiles.push(sourceFiles[index]);
   console.log("needAsyncFile-->"+sourceFiles[index]);
  }

 }
 return needCopyFiles;
}

//同步文件
function copyFile(dirName) {
 var sourcePath = path.pathOne + dirName +"/";
 var distPath = path.pathTwo + dirName +"/";

 readDir(dirName)
 useFileCopy(sourcePath,distPath,needCopyFiles(dirFilesOne,dirFilesTwo));

 readDir(dirName);
 useFileCopy(distPath,sourcePath,needCopyFiles(dirFilesTwo,dirFilesOne));
}

//for (var index in asyncDir) {
// //console.log(asyncDir[index])
// console.log(new Date() +" 执行同步--->"+asyncDir[index])
// copyFile(asyncDir[index]);
//}

var sched = later.parse.recur().every(10).second(),
 t = later.setInterval(function() {
  for (var index in asyncDir) {
   //console.log(asyncDir[index])
   console.log(new Date() +" 执行同步--->"+asyncDir[index]);
   copyFile(asyncDir[index]);
  }
 }, sched);

代码只是能用,菜鸟写法,等js这块有深入理解了之后,再修改这块的代码,也希望js大牛指点。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

展开阅读全文

更多Javascript文章

jquery限定文本框只能输入数字即整数和小数
Nov 29 24
浅析JavaScriptSerializer类的序列化与反序列化
Nov 22 19
jQuery移除或禁用html元素点击事件常用方法小结
Feb 10 11
详谈构造函数加括号与不加括号的区别
Oct 26 26
解决layui上传文件提示上传异常,实际文件已经上传成功的问题
Aug 19 24
快速解决layui弹窗按enter键不停弹窗的问题
Sep 18 22
JS实现网页时钟特效
Mar 25 25
手机访问当前页面