UNPKG

pooliot-client

Version:
95 lines (79 loc) 2.77 kB
import { spawn, spawnSync } from 'child_process'; import Logger from 'nightingale'; import { user } from '../params'; const logger = new Logger('app:commands:exec'); const scriptDirname = `${__dirname}/../../../scripts/`; type StdioOptionValueType = 'ignore' | 'pipe' | 'inherit'; type StdioOptionType = StdioOptionValueType | Array<StdioOptionValueType | any>; type RunOptionsType = {| cwd?: ?string, env?: ?Object, stdio?: ?StdioOptionType, |}; type ArgsType = Array<string | number>; export const runSync = (script: string, args: ArgsType = [], { cwd, env }: RunOptionsType = {}) => { logger.debug('run', { script, args, cwd, env }); const result = spawnSync(script, args, { cwd: cwd || scriptDirname, env: env && { ...process.env, ...env }, }); if (result.error) { logger.error(result.error.message); } if (result.stderr) { const stderr = result.stderr.toString(); if (stderr) { logger.error(stderr, { script, args, env }); } } if (result.stdout) { const stdout = result.stdout.toString().trim(); logger.debug(stdout, { script, args }); return stdout; } else { return ''; } }; export const runSyncOk = ( script: string, args: ArgsType = [], { cwd, env }: RunOptionsType = {}, ) => { const result = spawnSync(script, args, { cwd: cwd || scriptDirname, env }); return !result.status; }; export const runSyncAsUser = ( script: string, args: ArgsType, { cwd, env }: RunOptionsType = {}, ) => { if (env) throw new Error('env not supported in runSyncAsUser'); return runSync('sudo', ['-u', user, script, ...args], { cwd }); }; export const runAsync = (script: string, args: ArgsType, { cwd, env }: RunOptionsType = {}) => { logger.info('exec', { script, args }); const childProcess = spawn(script, args, { cwd: cwd || scriptDirname, env, stdio: 'pipe' }); childProcess.stdout.on('data', data => logger.debug(data.toString())); childProcess.stderr.on('data', data => logger.error(data.toString())); return childProcess; }; export const runAsyncAsUser = (script: string, args: ArgsType) => runAsync('sudo', ['-u', user, script, ...args]); export const runPipe = (script: string, args: ArgsType, { cwd, env }: RunOptionsType = {}) => { logger.debug('pipe', { script, args, cwd, env }); const result = spawnSync(script, args, { cwd: cwd || scriptDirname, env }); if (result.error) { logger.error(result.error.message); return null; } if (result.stderr) { const stderr = result.stderr.toString(); if (stderr) { logger.error(stderr, { script, args }); return null; } } return result.stdout; }; export const runPipeAsUser = (script: string, args: ArgsType) => runPipe('sudo', ['-u', user, script, ...args]);