package.json{ "name": "asyncFile", "version": "0.0.1", "dependencies":{ "fs-sync":"", "later":"" }}
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);