欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Nodejs实现多文件夹文件同步

程序员文章站 2023-09-04 14:26:20
本文实例为大家分享了nodejs实现多文件夹文件同步的具体代码,供大家参考,具体内容如下 package.json { "name": "async...

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

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