node.js實現自動打包上傳

不多說,直接上代碼了

config.js文件
module.exports = {
    sit: {
        remotePath: '',//上傳的遠程服務器的目錄
        username: '',//用戶名   
        password: '',//密碼
        host: '0.0.0.0',//遠程主機
        port: 0//服務器端口號
    }
}
deploy.js文件

const Client = require('ssh2').Client
const spawn = require("cross-spawn")
const path = require('path')
const ora = require('ora');
const glob = require("glob")
const env = process.argv[process.argv.length - 1].replace('--', '')
let config = require('./config.js')[env];

if (!config) {
    console.log(`找不到${env}環境用戶配置文件`)
    return
}
const cwd = path.dirname(__dirname)

const spinner = ora('開始打包...').start();
const remotePath = config.remotePath
console.log(`構建命令:build${env}`)
const build = spawn('yarn', [`build${env}`], {
    cwd: cwd
})
build.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
});
build.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
});
build.on('error', function(err) {
    console.log('error:', err)
    handleError(err, spinner)
})
build.on('close', function(code) {
    if (code !== 0) {
        console.log('打包失敗', code)
        spinner.stop()
        return
    }
    spinner.text = "打包完成,開始上傳..."
    const conn = new Client();
    conn.on('ready', function() {
        glob('**/*.*', {
            cwd: path.join(cwd, 'dist')
        }, function(err, files) {
            if (err) {
                handleError(err, spinner)
                return
            }
            let length = files.length,
                index = 0
            conn.sftp((err, sftp) => {
                if (err) {
                    handleError(err, spinner)
                    return
                }
                spinner.stop()
                const upload = () => {
                    const currentFile = files[index++]
                    if (!currentFile || index > length) {
                        console.log('上傳完畢')
                        conn.end();
                        return;
                    }
                    sftp.fastPut(path.join(cwd, 'dist', currentFile), path.join(remotePath, currentFile).replace(/\\/g, '/'), function(err, result) {
                        if (err) {
                            console.log(err, '出錯了')
                            return
                        }
                        console.log(`${currentFile}上傳成功`)
                        upload()
                    });
                }
                upload()
            })
        })

    }).connect({
        host: config.host,
        port: config.port,
        username: config.username,
        password: config.password
    });

})

const handleError = (err, spinner) => {
    console.log(err)
    spinner.stop()
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容