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;
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);}