Node.js基于Webpack Watch实现SFTP自动上传脚本
本文介绍在Node.js开发环境中,利用Webpack的watch监听功能配合ssh2-sftp-client插件,实现代码构建后自动上传至SFTP服务器的自动化脚本。文章详细讲解了连接配置、文件类型处理及目录存在的注意事项,旨在简化本地开发与远程测试的部署流程。
背景与动机
起因
在加入一个新的小组进行项目开发时,开发环境基于Node.js,通过Webpack打包构建代码,随后上传至SFTP服务器,最后在浏览器中进行测试。这种开发模式本身并无不妥,但每次修改源代码后都需要执行build和upload操作,过程繁琐且令人疲惫。虽然之前的项目中存在gulp-sftp任务脚本,但并未生效。因此,决定自力更生,开发一个自动上传SFTP的服务脚本。
设想
实现思路
由于项目基于Webpack,可以直接启动Webpack的编译watch监听功能。在watch的回调函数中执行SFTP上传操作,并通过npm社区寻找合适的SFTP客户端插件。
实现
代码实现
这里使用了插件ssh2-sftp-client,其文档中包含了使用说明和API接口。
编写了一个sftp模块,在建立连接后直接导出该实例。
const Client = require('ssh2-sftp-client');
const fs = require('fs');
const sftp = new Client();
sftp
.connect({
host: '0.0.0.0', // ftp服务器ip地址
port: '22', // ftp服务器port
username: 'yourname', // 你的登录用户名
password: 'yourpass', // 你的密码
privateKey: fs.readFileSync('/Users/yourname/.ssh/id_rsa'), // 私钥
passphrase: 'yourpass', // 私钥密码
})
.then(() => {
console.log('ftp文件服务器连接成功');
})
.catch(err => {
console.log(err, 'catch error');
});
module.exports = sftp;
随后在Webpack的watch监听中进行文件上传操作。关于上传文件,对于图片等特定类型需要使用Buffer类型进行上传,因此需要对此进行特殊处理。
const path = require('path');
const fs = require('fs');
const yargs = require('yargs');
const webpack = require('webpack');
const webpackConfig = require('./webpack.prod.config');
const sftp = require('./sftp');
const user = yargs.argv.user || '';
console.log(user);
const staticFilesPath = {
js: {
local: path.resolve(__dirname, '../dist/js'),
remote: `/upload_code/${user}/static/mobile/js/dist`,
},
css: {
local: path.resolve(__dirname, '../dist/css'),
remote: `/upload_code/${user}/static/mobile/css/`,
},
img: {
local: path.resolve(__dirname, '../dist/images'),
remote: `/upload_code/${user}/static/mobile/images/`,
},
};
let isFirstBuild = true;
const compiler = webpack(webpackConfig);
const watching = compiler.watch(
{
ignored: /node_modules/,
aggregateTimeout: 100,
poll: 1000,
},
(err, stats) => {
if (err || stats.hasErrors()) {
console.log(err);
}
console.log('编译成功!');
if (isFirstBuild) {
isFirstBuild = false;
return;
}
console.log('正在上传...');
uploadFile()
.then(() => {
console.log('------所有文件上传完成!-------\n');
})
.catch(() => {
console.log('------上传失败,请检查!-------\n');
});
}
);
/**
* 处理文件路径,循环所有文件,如果是图片需要读取成Buffer类型
**/
function handleFilePath(obj, type) {
const { local, remote } = obj;
const files = fs.readdirSync(local);
return files.map(file => {
const _lp = `${local}/${file}`;
return {
type: type,
file: file,
localPath: type !== 'img' ? _lp : fs.readFileSync(_lp),
remotePath: `${remote}/${file}`,
};
});
}
/**
* 上传文件
**/
function uploadFile() {
let files = [];
Object.keys(staticFilesPath).forEach(key => {
files = files.concat(handleFilePath(staticFilesPath[key], key));
});
const tasks = files.map(item => {
return new Promise((resolve, reject) => {
sftp
.put(item.localPath, item.remotePath)
.then(() => {
console.log(`${item.file}上传完成`);
resolve();
})
.catch(err => {
console.log(`${item.file}上传失败`);
reject();
});
});
});
return Promise.all(tasks);
}
关键注意事项
注意点:
- 连接SFTP服务器时,推荐使用私钥文件进行连接,使用密码方式出错的可能性较大。
- 在上传文件部分,目前该插件不支持直接上传整个目录,因此需要循环处理文件。
- 在上传文件部分,容易出错,务必保证远端服务器存在对应的目录,因为目前该插件没有自动创建目录的机制。
总结
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对本站的支持。
在 NestJS 中使用管道验证数据与守卫控制访问权限
2026-11-05 12:43:41
Node.js后端生成高强度随机字符串的方法
2026-11-04 16:29:54
Node.js环境中怎么使用axios或http模块发送GET请求
2026-11-03 21:57:15
Node.js环境下怎么实现JS反混淆自动化?常用库与CLI工具推荐
2026-11-03 21:15:54
解决JS逆向常见报错:缺少DOM环境导致代码运行失败
2026-11-03 20:41:59
