UNPKG

server-deploy-cli

Version:

connect server with ssh2-sftp-client, and publish local files to remote server or delete some files from the remote server or other operations you wanna do

86 lines (78 loc) 3.26 kB
/* * @Author: famous * @Date: 2022-09-21 09:13:23 * @Last Modified by: famous * @Last Modified time: 2023-07-11 11:34:13 * * @type * single: 执行单句命令,例如: npm run build * file: 执行 sh 文件命令 * * @shell * windows 中默认的 cmd 或 powershell 终端无法正常执行 sh 文件中的命令,故使用 Git Bash 执行 * windows 中请传入 Git Bash 的 sh.exe 或 bash.exe 文件在安装目录中的路径 * 默认值: 'C:\\Program Files\\Git\\bin\\sh.exe' * */ // const Log = require('./log') // const os = require('os') // Log.high(`type: ${os.type()}\nplatform: ${os.platform()}\nEOL: ${os.EOL}`) // child_process 可执行 cmd 、 bat 或 sh 等文件,这里统一执行 sh 文件 // const cp = require('child_process') import Log from "./log.js" import os from 'os' import cp from 'child_process' import concatStream from 'concat-stream' export default (cmd, type = 'single', shell) => { return new Promise((resolve, reject) => { let subprocess, errMsg = '' if (type === 'single') { // 也可以执行Windows中的 cmd 或 bat 文件 subprocess = cp.exec(cmd) } else if (type === 'file') { const systemType = os.type() if (systemType.indexOf('Windows') > -1) { //Windows subprocess = cp.exec(cmd, { shell }) } else { //other system type , Linux 、 Mac and so on subprocess = cp.spawn('sh', [cmd]) } } else { Log.error(`current subprocess do not support type: ${ type }`) return reject(`current subprocess do not support type: ${ type }`) } /** * 若输出信息特别多可能使缓冲区被快速填满导致不触发 subprocess.stdout.on('end') 使进程卡住,故此处将stdout流导向另一个可以管理的流 * 具体可参考 ./images/child_process.stdout不触发end原因及解决方案.jpg */ // subprocess.stdout.on('data', (data) => { // Log.high(`\nsubprocess.stdout ondata: ${data}`) // }) subprocess.stdout.pipe(concatStream(data => { // 完整的输出数据 Log.high(`\nsubprocess.stdout ondata: ${data.toString()}`) })) subprocess.stdout.on('end', () => { Log.high(`subprocess.stdout onend`) }) // subprocess.stderr.on('data', (data) => { // Log.info(`subprocess occurred stderr: ${data}`) // errMsg += data // }) subprocess.stderr.pipe(concatStream(data => { errMsg += data.toString() })) subprocess.on('error', err => { errMsg += err }) subprocess.on('close', (code, signal) => { // 执行完成后正常退出 code 为 0 if (code === 0) { Log.success(`\n子进程执行完成,code: ${code}`) return resolve() // 执行完毕后, resolve } Log.error(`subprocess exited with code: ${code} & signal: ${signal}`) reject(errMsg) }) }) }