node 写个 检测 文件的变化并上传

其实 这个 网上有类似教程 但是一开始 我没搜到 然后我的思路 就想着 先找一个能监听文件变化的方法 再找一个 node 使用sftp的方法

然后找到了两个库 分别是 chokidar (用监听文件变化)  ssh2-sftp-client(用于sftp)

然后 有些需要注意的 一般只能监听 一个文件的改动 然后 上传一个文件  如果想监听 一个文件夹  那就只能监听文件夹里所有文件  好在 chokidar 帮我们解决了  传入 一个文件夹名字就行 然后 node 里 文件的change 事件会触发非常多次 

但是这个库也帮我们解决了😂 所以 我们还是看代码吧

 1 var chokidar = require('chokidar');
 2 let Client = require('ssh2-sftp-client');
 3 var localBasePath = '本地的路径';
 4 var remoteBasePath = '服务器的路径';
 5 var watchPath = '本地要监听的目录'
 6 var remoteReplace = '当服务器 和 本地 目录不一样需要替换时 这里填写服务器的目录 若一样 和上面的相同即可'
 7 
 8 
 9 
10 var watchList = [
11     new RegExp(watchPath + '/目标文件夹里有些需要监听 有些不需要时/'),
12 ]
13 
14 var watcher = chokidar.watch(watchPath, {
15   ignored: /[\/\\]\./, persistent: true
16 });
17  
18 var log = console.log.bind(console);
19 
20 
21 
22 watcher.on('change', function(path) {
23     for(let i = 0; i < watchList.length; i++) {
24         const element = watchList[i];
25         if (element.test(path)) {
26             var remoteReplacePath = remoteBasePath + path.replace(new RegExp(remoteReplace), '')
27             log('File', path, 'has been changed', '改了改了改了');
28             log(localBasePath + path, remoteReplacePath, '????')
29             put(localBasePath + path, remoteReplacePath)
30         }
31     }
32 })
33 
34 function put(localPath,romotePath){
35     let sftp = new Client();
36     sftp.connect({
37         host: '服务器的 这个自己填',
38         port: '这个自己填',
39         username: '这个自己填',
40         password: '这个自己填'
41     }).then(() => {
42         return sftp.put(localPath, romotePath, [false], ['utf8']);
43     }).then(() =>{
44         console.log("上传完成");
45     }).catch((err) => {
46         console.log(err, 'catch error');
47     });
48 }

这个其实不复杂 而且效果一般 我自己使用过 有时候第一次并没有传成功 需要再传一次 感觉 不是很理想 这个东西

posted @ 2018-10-08 14:33  切图仔xx  阅读(697)  评论(0编辑  收藏  举报