nodejs 监控代码变动实现ftp上传
被动模式下
//https://www.npmjs.com/package/watch
//文件同步功能
var watch = require('watch');
var path = require("path");
var fs = require('fs');
var http = require('http');
const ftp = require("basic-ftp");
var files=[];
var config={
//remote_root:'/Users/apple/kefu/',
// host:'192.168.1.159',
// username:'apple',
// password:'123',
remote_root:'/',
host:'127.0.0.1',
username:'aaaa',
password:'aaaa',
};
//需要忽略的文件或目录
var ignore=[
__dirname+'\\file',
]; function readDirSync(path){
var files=[];
var pa = fs.readdirSync(path);
pa.forEach(function(ele,index){
var info = fs.statSync(path+"/"+ele);
if(info.isDirectory()){
files=files.concat(readDirSync(path+"/"+ele));
}else{
files.push(path+"/"+ele);
}
})
return files;
} console.log('start watching');
watch.createMonitor(__dirname,{ignoreDotFiles:true}, function (monitor) {
monitor.on("created", function (f, stat) {
for(var i=0;i<ignore.length;i++){
if(f.indexOf(ignore[i])>=0) return;
}
// Handle new files
console.log("created:",f);
var stats=fs.statSync(f);
if(stats.isDirectory()){
var folder_files=readDirSync(f);
for(var i=0;i<folder_files.length;i++){
console.log("created:",folder_files[i]);
if(files.indexOf(folder_files[i])===-1) files.push(folder_files[i]);
}
}else if(stats.isFile()){
if(files.indexOf(f)===-1) files.push(f);
}
})
monitor.on("changed", function (f, curr, prev) {
for(var i=0;i<ignore.length;i++){
if(f.indexOf(ignore[i])>=0) return;
}
// Handle file changes
console.log("changed:",f);
if(files.indexOf(f)===-1) files.push(f);
})
monitor.on("removed", function (f, stat) {
for(var i=0;i<ignore.length;i++){
if(f.indexOf(ignore[i])>=0) return;
}
// Handle removed files
console.log("removed:",f); }) });
async function upload(){ console.log('start to upload');
//https://www.npmjs.com/package/basic-ftp
const client = new ftp.Client();
client.ftp.verbose = true;
try {
await client.connect(config.host, 21);
// await client.useTLS();
await client.login(config.username, config.password);
await client.useDefaultSettings();
//await client.upload(fs.createReadStream("README.md"), "README.md"); //上传目录 避免中文
//console.log(await client.list()); //read file
console.log('begin to upload');
if(!files.length){
console.log('no files to upload');
return;
}
var contents=files; for(var i=0;i<contents.length;i++){
var roots=contents[i].trim();
if(!roots) continue;
if(!fs.existsSync(roots)) continue;
roots=roots.replace(/\\/g,'/');
//E:/wwwroot2/kefuv3/application/models/0/usersModel.class.php
var local_file=roots;
var local_path=path.dirname(local_file);
var remote_path=local_path.replace(__dirname.replace(/\\/g,'/'),'').substr(1);
//Users/apple/kefu/application/models/0/usersModel.class.php
var remote_file=local_file.replace(__dirname.replace(/\\/g,'/'),'').substr(1);
//dir
await client.ensureDir(config.remote_root+remote_path);
//change dir
await client.cd(config.remote_root+remote_path);
//upload
await client.upload(fs.createReadStream(local_file), path.basename(local_file)); }
files=[];
console.log('upload finished!'); }
catch(err) {
console.log(err);
}
client.close(); }
var x=0;
//http://nodejs.cn//api/process.html#process_signal_events
process.stdin.resume(); process.on('SIGINT', () => {
// x++;
// if(x==2){
// console.log('byebye');
// process.exit(0);
// }
upload(); });
主动模式下
//https://www.npmjs.com/package/watch
//https://blog.csdn.net/zgljl2012/article/details/50365492
//文件同步功能
var watch = require('watch');
var path = require("path");
var fs = require('fs');
var p = require('child_process');
var iconv = require("iconv-lite");
var files=[]; var config={
//remote_root:'/Users/apple/kefu/',
// host:'192.168.1.159',
// username:'apple',
// password:'123',
remote_root:'/',
host:'127.0.0.1',
username:'',
password:'',
}; //需要忽略的文件或目录
var ignore=[
__dirname+'\\file',
__dirname+'\\cmd.txt',
]; function readDirSync(path){
var files=[];
var pa = fs.readdirSync(path);
pa.forEach(function(ele,index){
var info = fs.statSync(path+"/"+ele);
if(info.isDirectory()){
files=files.concat(readDirSync(path+"/"+ele));
}else{
files.push(path+"/"+ele);
}
})
return files;
} console.log('start watching');
watch.createMonitor(__dirname,{ignoreDotFiles:true}, function (monitor) {
monitor.on("created", function (f, stat) {
for(var i=0;i<ignore.length;i++){
if(f.indexOf(ignore[i])>=0) return;
}
// Handle new files
console.log("created:",f);
var stats=fs.statSync(f);
if(stats.isDirectory()){
var folder_files=readDirSync(f);
for(var i=0;i<folder_files.length;i++){
console.log("created:",folder_files[i]);
if(files.indexOf(folder_files[i])===-1) files.push(folder_files[i]);
}
}else if(stats.isFile()){
if(files.indexOf(f)===-1) files.push(f);
}
})
monitor.on("changed", function (f, curr, prev) {
for(var i=0;i<ignore.length;i++){
if(f.indexOf(ignore[i])>=0) return;
}
// Handle file changes
console.log("changed:",f);
if(files.indexOf(f)===-1) files.push(f);
})
monitor.on("removed", function (f, stat) {
for(var i=0;i<ignore.length;i++){
if(f.indexOf(ignore[i])>=0) return;
}
// Handle removed files
console.log("removed:",f); }) });
function create_dir_cmd(remote_root,remote_path){
// a/b/c
if(!remote_path) return '';
var folder=remote_path.split('/');
var cmd='';
var base=remote_root;
for(let i=0;i<folder.length;i++){
if(!folder[i]) continue;
base+=folder[i]+'/';
cmd+="mkdir "+base+"\n";
}
return cmd;
}
function upload(){ console.log('begin to upload');
if(!files.length){
console.log('no files to upload');
return;
} var son=''; var contents=files;
for(var i=0;i<contents.length;i++){
var roots=contents[i].trim();
if(!roots) continue;
if(!fs.existsSync(roots)) continue;
roots=roots.replace(/\\/g,'/');
//E:/wwwroot2/kefuv3/application/models/0/usersModel.class.php
var local_file=roots;
var local_path=path.dirname(local_file);
var remote_path=local_path.replace(__dirname.replace(/\\/g,'/'),'').substr(1);
//Users/apple/kefu/application/models/0/usersModel.class.php
var remote_file=local_file.replace(__dirname.replace(/\\/g,'/'),'').substr(1);
//dir
//await client.ensureDir(config.remote_root+remote_path);
//change dir
//await client.cd(config.remote_root+remote_path);
//upload
//await client.upload(fs.createReadStream(local_file), path.basename(local_file));
son+=create_dir_cmd(config.remote_root,remote_path);//mkdir
son+="cd "+config.remote_root+remote_path+"\n";//change dir
son+="put \""+local_file+"\" \""+path.basename(local_file)+"\"\n";//upload
} var str=`open ${config.host}
${config.username}
${config.password}
binary
prompt off
pwd
${son}
close
quit
`; var flag=fs.writeFile('cmd.txt', str,(err) => {
if (err) throw err;
console.log('cmd.txt保存成功!'); p.exec('ftp -s:cmd.txt', { encoding: 'binary' },function (error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
}
console.log(iconv.decode(Buffer.from(stdout, 'binary'), 'cp936')); files=[];
console.log('upload finished!');
}); }); } var x=0;
//http://nodejs.cn//api/process.html#process_signal_events
process.stdin.resume(); process.on('SIGINT', () => {
// x++;
// if(x==2){
// console.log('byebye');
// process.exit(0);
// }
upload(); });
建议使用第二种,使用的是windows的ftp命令,兼容了主动模式
watch.bat
node watch.js
pause
使用时双击watch.bat
需要上传时按ctrl+c
nodejs 监控代码变动实现ftp上传的更多相关文章
- python 网络编程粘包解决方案2 + ftp上传 + socketserver
一.struct 神奇的打包工具 struct 代码: import struct num = 156 #将int类型的数据打包成4个字节的数据 num_stru = struct.pack('i', ...
- ftp上传java代码
<欢迎转载http://www.cnblogs.com/shizhongtao/p/3345826.html> 上传代码就写个简单的小例子.首先要加入jar包.commons-net-1. ...
- C# FTP上传文件至服务器代码
C# FTP上传文件至服务器代码 /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo ...
- python之实现ftp上传下载代码(含错误处理)
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kait ...
- python之模块ftplib(实现ftp上传下载代码)
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块ftplib(实现ftp上传下载代码) #需求:实现ftp上传下载代码(不含错误处理) f ...
- 超实用文件监控多线程FTP上传工具
这是自己很久以前写的一个多线程FTP 上传工具,支持多账户,自定义线程数,自定义文件监控目录,可用做文件发布使用,非常实用,今天有小伙伴问起,现分享出来: using System; using Sy ...
- .net FTP上传文件
FTP上传文件代码实现: private void UploadFileByWebClient() { WebClient webClient = new WebClient(); webClient ...
- FTP上传文件到服务器
一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...
- FTP上传文件提示550错误原因分析。
今天测试FTP上传文件功能,同样的代码从自己的Demo移到正式的代码中,不能实现功能,并报 Stream rs = ftp.GetRequestStream()提示远程服务器返回错误: (550) 文 ...
随机推荐
- mysql 表格操作指令大全(Show、desc、create、insert into、delete、select、drop、update、alter)
使用数据库 use 数据库名 eg: use weiying 2. 查看库里所有的表 Show tables 3.查看所表的结构 desc 表名 desc score 4.建表create tabl ...
- 在TortoiseSVN使用clean up
1.在[Cleanup]窗体中勾选中复选框[Clean up working copy status],选中该复选框表示解除锁定. 2.在[Cleanup]窗体中勾选中复选框[revert all c ...
- 【转】HTTP学习---TCP和UDP协议的区别与应用
[原文]https://www.toutiao.com/i6592813624689951239/ 概述 ⊙TCP/IP是个协议组,可分为三个层次:网络层.传输层和应用层. 在网络层有IP协议.ICM ...
- MySQL核心之双一原则
所谓的双一就是指: sync_binlog=; innodb_flush_log_at_trx_commit= innodb_flush_log_at_trx_commit和sync_binlog这两 ...
- October 31st, 2017 Week 44th Tuesday
No matter how hard the past is, you can always begin again. 不管过去有多么困难,你都可以重新开始. Honestly, I don't ag ...
- 团队作业——Beta冲刺3
团队作业--Beta冲刺 冲刺任务安排 杨光海天 今日任务:浏览详情界面的开发 明日任务:浏览详情界面的开发 吴松青 今日任务:与队长一同进行图片详情的开发,接触了一些自己没接触过的知识点并向队友学习 ...
- 以太坊预言机与WEB API(原创,转载请说明原址)
什么是预言机? 从链外获得数据,提供区块链与现实世界事件之间的连接,提供外部信息的平台 预言机自身也是一种智能合约,它允许区块链连接到任何现有的API 是这个预言机去调用各种 WEB API的接口 这 ...
- nginx 服务器在上传文件出现413代码的解决方法
打开nginx主配置文件nginx.conf 找到http{}段,添加client_max_body_size 20m;
- Apache服务器的安装与配置
文档:http://httpd.apache.org/docs/2.4/ 指令:http://httpd.apache.org/docs/2.4/mod/core.html 一.配置文件 语法 * 主 ...
- 错误 ORA-01102: cannot mount database in EXCLUSIVE mode 的处理方法
今天启动数据库时报错了! SQL> startup mount ORACLE instance started. Total System Global Area 608174080 byte ...