起因
剛加入一個小組的項目開發,開發環境是基于node環境,通過webpack打包構建代碼,然后上傳sftp,在瀏覽器測試。這種開發模式無可厚非,但是每次修改源代碼,然后build,然后upload,不勝其煩。之前項目中有過 gulp-sftp任務腳本,然而并不是生效。于是自力更生,另謀他法,搞一個自動上傳sftp的服務腳本。
設想
因為基于webpack,所以直接啟動webpack編譯的watch監聽即可,在watch回調里執行stfp的上傳,上傳去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); }
注意點:
總結
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com