Nodejs实现多文件夹文件同步

只有相信自己的目标,努力工作和奋斗的人才能取得最终的成功。但是我一直相信的一件事是,当您触摸自己哭泣时,您就成功了!

本文实例为大家分享了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大牛指点。

到此这篇关于Nodejs实现多文件夹文件同步就介绍到这了。对待生命你不妨大胆冒险一点儿,因为好歹你要失去它。更多相关Nodejs实现多文件夹文件同步内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
nodejs二进制与Buffer的介绍与使用

nodejs中各种加密算法的实现详解

独立部署小程序基于nodejs的服务器过程详解

NodeJs 模仿SIP话机注册的方法

nodejs实现获取本地文件夹下图片信息功能示例