child_process#spawn JavaScript Examples
The following examples show how to use
child_process#spawn.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: _util.js From ctzn with MIT License | 7 votes |
export async function createServer () {
const tmpdir = await tmp.dir({unsafeCleanup: true})
const domain = `dev${nServer++}.localhost`
const port = DEBUG_MODE_PORTS_MAP[domain]
console.log('Storing config in', tmpdir.path)
const binPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin.js')
const serverProcess = spawn(
'node',
[binPath, 'start-test', '--configDir', tmpdir.path, '--domain', domain],
{
stdio: [process.stdin, process.stdout, process.stderr],
env: INSPECTOR_ENABLED ? Object.assign({}, process.env, {NODE_OPTIONS: `--inspect=localhost:${5555+nServer}`}) : undefined
}
)
const client = new WsClient(`ws://localhost:${port}/`)
const api = await createRpcApi(client)
await api.debug.whenServerReady()
return {
url: `http://localhost:${port}/`,
domain,
serverUserId: `server@${domain}`,
client,
api,
process: serverProcess,
close: async () => {
const p = new Promise(r => {
if (serverProcess.exitCode !== null) r()
serverProcess.on('exit', r)
})
serverProcess.kill()
await p
await tmpdir.cleanup()
}
}
}
Example #2
Source File: util.js From riju with MIT License | 7 votes |
export async function run(args, log, options) {
options = options || {};
const input = options.input;
const check = options.check === undefined ? true : options.check;
const suppressOutput = options.suppressOutput || false;
delete options.input;
delete options.check;
const proc = spawn(args[0], args.slice(1), options);
if (typeof input === "string") {
proc.stdin.end(input);
}
let output = "";
proc.stdout.on("data", (data) => {
output += `${data}`;
});
proc.stderr.on("data", (data) => {
output += `${data}`;
});
return await new Promise((resolve, reject) => {
proc.on("error", reject);
proc.on("close", (code, signal) => {
output = output.trim();
if (output && !suppressOutput) {
log(`Output from ${args[0]}:\n` + output);
}
if (code === 0 || !check) {
resolve({ code, output });
} else {
reject(`command ${args[0]} failed with error code ${signal || code}`);
}
});
});
}
Example #3
Source File: converter.js From HinataMd with GNU General Public License v3.0 | 6 votes |
function ffmpeg(buffer, args = [], ext = '', ext2 = '') {
return new Promise(async (resolve, reject) => {
try {
let tmp = join(global.__dirname(import.meta.url), '../tmp', + new Date + '.' + ext)
let out = tmp + '.' + ext2
await promises.writeFile(tmp, buffer)
spawn('ffmpeg', [
'-y',
'-i', tmp,
...args,
out
])
.on('error', reject)
.on('close', async (code) => {
try {
await promises.unlink(tmp)
if (code !== 0) return reject(code)
resolve({
data: await promises.readFile(out),
filename: out,
delete() {
return promises.unlink(out)
}
})
} catch (e) {
reject(e)
}
})
} catch (e) {
reject(e)
}
})
}
Example #4
Source File: CommonUtils.js From HandyHost with GNU Lesser General Public License v2.1 | 6 votes |
getIPForDisplay(){
return new Promise((resolve,reject)=>{
let getIPCommand;
let getIPOpts;
let ipCommand;
let ipOut;
if(process.platform == 'darwin'){
getIPCommand = 'ipconfig';
getIPOpts = ['getifaddr', 'en0'];
}
if(process.platform == 'linux'){
//hostname -I [0]
getIPCommand = 'hostname';
getIPOpts = ['-I'];
}
ipCommand = spawn(getIPCommand,getIPOpts);
ipCommand.stdout.on('data',d=>{
ipOut = d.toString('utf8').trim();
});
ipCommand.on('close',()=>{
if(process.platform == 'linux'){
ipOut = ipOut.split(' ')[0];
}
resolve({ip:ipOut,port:this.port,sslPort:this.sslPort});
});
});
}
Example #5
Source File: devserver.js From juggernaut-desktop with MIT License | 6 votes |
devServer = {
port,
hot: true,
publicPath,
headers: { 'Access-Control-Allow-Origin': '*' },
watchOptions: {
aggregateTimeout: 300,
ignored: /node_modules/,
poll: 100
},
historyApiFallback: true,
// Start the main process as soon as the server is listening.
after: () => {
if (process.env.HOT) {
spawn('npm', ['run', 'start-main-dev'], {
shell: true,
env: process.env,
stdio: 'inherit'
})
.on('close', code => process.exit(code))
.on('error', spawnError => mainLog.error(spawnError));
}
}
}
Example #6
Source File: Runner.js From axe-api with MIT License | 6 votes |
constructor(name) {
console.log("runner", name);
this.child = spawn("node", ["serve.js", name]);
this.child.stdout.on("data", (data) => {
process.stdout.write(`${data}`);
});
this.child.stderr.on("data", (data) => {
console.error(`stderr: ${data}`);
});
}
Example #7
Source File: global-setup-jest.js From gatsby-source-wordpress-experimental with MIT License | 6 votes |
module.exports = async function globalSetup() {
if (!process.env.START_SERVER) {
return
}
if (!process.env.WORDPRESS_BASIC_AUTH) {
console.log(
`Please add the env var WORDPRESS_BASIC_AUTH. It should be a string in the following pattern: base64Encode(\`\${username}:\${password}\`)`
)
await new Promise((resolve) => setTimeout(resolve, 100))
process.exit(1)
}
if (process.env.WPGQL_INCREMENT) {
const response = await mutateSchema()
console.log(response)
} else {
const response = await resetSchema()
console.log(response)
}
console.log(`\nstarting Gatsby`)
const gatsbyProcess = spawn(`yarn`, [`develop-test-runtime`], {
detached: true,
env: {
...process.env,
NODE_ENV: `development`,
},
})
global.__GATSBY_PROCESS = gatsbyProcess
gatsbyProcess.stdout.pipe(process.stdout)
await on({ resources: [`http://localhost:8000`] })
}
Example #8
Source File: cli.js From VoltranJS with MIT License | 6 votes |
function serve(voltranConfigs) {
console.log(clc.green('Project Serve is starting...'));
const out = spawn('node', [
'-r',
'source-map-support/register',
'--max-http-header-size=20480',
`${voltranConfigs.distFolder}/server/server.js`
], {env: {'NODE_ENV': 'production', ...process.env}});
out.stdout.on('data', (data) => {
console.log(data.toString());
});
out.stderr.on('data', (data) => {
console.error(data.toString());
});
out.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
}
Example #9
Source File: index.js From cli with MIT License | 6 votes |
async function startDaemon (name, readable) {
const require = createRequire(import.meta.url)
const daemonRoot = p.dirname(require.resolve(name))
const binPath = p.join(daemonRoot, 'bin', 'index.js')
console.error(`${readable} daemon started`)
return spawn('node', [binPath], {
detached: true
})
}
Example #10
Source File: WinSquirrelStartupEventHandler.js From makerverse with GNU General Public License v3.0 | 6 votes |
run = (args, done) => {
const appPath = path.resolve(process.execPath, '..');
const rootAtomPath = path.resolve(appPath, '..');
const updateExe = path.resolve(path.join(rootAtomPath, 'Update.exe'));
log.debug('Spawning `%s` with args `%s`', updateExe, args);
spawn(updateExe, args, { detached: true })
.on('close', done);
}
Example #11
Source File: cli.js From freyr-js with Apache License 2.0 | 6 votes |
function wrapCliInterface(binaryNames, binaryPath) {
binaryNames = Array.isArray(binaryNames) ? binaryNames : [binaryNames];
const isWin = process.platform === 'win32';
const path = xpath.join(__dirname, 'bins', isWin ? 'windows' : 'posix');
if (!binaryPath) {
for (let name of binaryNames) {
if (!check_bin_is_existent(name, path)) continue;
binaryPath = ensureBinExtIfWindows(isWin, name);
break;
}
if (!binaryPath)
throw new Error(
`Unable to find an executable named ${(a =>
[a.slice(0, -1).join(', '), ...a.slice(-1)].filter(e => e != '').join(' or '))(binaryNames)}. Please install.`,
);
}
return (file, args, cb) => {
if (typeof file === 'string') spawn(binaryPath, [file, ...parseMeta(args)], {env: extendPathOnEnv(path)}).on('close', cb);
};
}
Example #12
Source File: Spawn.js From Lynx with MIT License | 6 votes |
start(done) {
this._startTime = Date.now();
try {
const stdio = this.options.log ? ["ignore", "inherit", "inherit"] : ["ignore", "ignore", "ignore"];
//console.log(this.script);
//console.log(this.args);
const prc = spawn(this.script, this.args, {
stdio: stdio,
env: this.env,
disconnected: false
});
prc.on("exit", code => {
clearTimeout(this._killTimeout);
this._processEnded(code, done);
});
this._killTimeout = this._buildTimeout();
this._pid = prc.pid;
} catch (ex) {
console.log("Distributor ERROR: " + ex + " just falling back to default error");
this._processEnded(99999, done);
}
return this;
}
Example #13
Source File: canvas.js From HinataMd with GNU General Public License v3.0 | 5 votes |
/**
* Levelup image
* @param {String} teks
* @param {Number} level
* @returns {Promise<Buffer>}
*/
export function levelup(teks, level) {
return new Promise(async (resolve, reject) => {
if (!(global.support.convert || global.support.magick || global.support.gm)) return reject('Not Support!')
const font = join(__dirname, '../src/font')
let fontLevel = join(font, './level_c.otf')
let fontTexts = join(font, './texts.otf')
let xtsx = join(__dirname, '../src/lvlup_template.jpg')
let anotations = '+1385+260' // gapake else if kadang error
if (level > 2) anotations = '+1370+260'
if (level > 10) anotations = '+1330+260'
if (level > 50) anotations = '+1310+260'
if (level > 100) anotations = '+1260+260'
const [_spawnprocess, ..._spawnargs] = [...(global.support.gm ? ['gm'] : global.support.magick ? ['magick'] : []),
'convert',
xtsx,
'-font',
fontTexts,
'-fill',
'#0F3E6A',
'-size',
'1024x784',
'-pointsize',
'68',
'-interline-spacing',
'-7.5',
'-annotate',
'+153+200',
teks,
//original together
'-font',
fontLevel,
'-fill',
'#0A2A48',
'-size',
'1024x784',
'-pointsize',
'140',
'-interline-spacing',
'-1.2',
'-annotate',
anotations,
level,
'-append',
'jpg:-'
]
let bufs = []
spawn(_spawnprocess, _spawnargs)
.on('error', reject)
.on('close', () => {
return resolve(Buffer.concat(bufs))
})
.stdout.on('data', chunk => bufs.push(chunk))
})
}
Example #14
Source File: HandySia.js From HandyHost with GNU Lesser General Public License v2.1 | 5 votes |
initHealthCheck(){
console.log('init SC health check interval')
if(typeof this.healthCheckInterval != "undefined"){
clearInterval(this.healthCheckInterval);
delete this.healthCheckInterval;
}
this.healthCheckInterval = setInterval(()=>{
//every 20 mins
checkHealth();
},1000*60*20)
const _this = this;
function checkHealth(){
//console.log('performing SC health check')
_this.daemon.getVersion().then(data=>{
//console.log('SC is alive')
}).catch(err=>{
console.log('SC health check error: siad must be down');
const didJustUpdateFileLoc = process.env.HOME+'/.HandyHost/siaData/isUpdating';
const didJustUpdate = fs.existsSync(didJustUpdateFileLoc);
if(didJustUpdate){
console.log('SC health check: looks like an update happened, hold off')
}
else{
console.log('starting healthcheck revival');
const logString = new Date()+' :: healthcheck is beginning\n';
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',logString,'utf8');
//first make sure theres not a zombie siad
const pkill = spawn('pkill',['-9','siad']);
pkill.stdout.on('data',d=>{
console.log('pkill out',d.toString());
const pkout = new Date()+' pkill stdout '+d.toString();
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',pkout,'utf8');
});
pkill.stderr.on('data',d=>{
console.log('pkill err',d.toString());
const pkout = new Date()+' pkill stderr '+d.toString();
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',pkout,'utf8');
})
pkill.on('close',()=>{
setTimeout(()=>{
const logString = new Date()+' :: pkill complete, healthcheck is restarting siad\n';
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',logString,'utf8');
_this.trySpawningSiad(true);
},120000)
})
//this.trySpawningSiad();
}
})
}
}
Example #15
Source File: gulpfile.babel.js From django-dashboard-light-blue with MIT License | 5 votes |
function npmPublish(done) {
spawn('npm', ['publish'], { stdio: 'inherit' }).on('close', done);
}
Example #16
Source File: spawnTestChild.js From ftx-cli with MIT License | 5 votes |
function spawnTestChild(command) {
return spawn(command, {
shell: true,
env: { ...process.env, NODE_ENV: 'test-child' },
});
}
Example #17
Source File: editor.js From ReactSourceCodeAnalyze with MIT License | 5 votes |
export function launchEditor(
maybeRelativePath: string,
lineNumber: number,
absoluteProjectRoots: Array<string>,
) {
const filePath = getValidFilePath(maybeRelativePath, absoluteProjectRoots);
if (filePath === null) {
return;
}
// Sanitize lineNumber to prevent malicious use on win32
// via: https://github.com/nodejs/node/blob/c3bb4b1aa5e907d489619fb43d233c3336bfc03d/lib/child_process.js#L333
if (lineNumber && isNaN(lineNumber)) {
return;
}
let [editor, ...args] = guessEditor();
if (!editor) {
return;
}
if (lineNumber) {
args = args.concat(getArgumentsForLineNumber(editor, filePath, lineNumber));
} else {
args.push(filePath);
}
if (childProcess && isTerminalEditor(editor)) {
// There's an existing editor process already and it's attached
// to the terminal, so go kill it. Otherwise two separate editor
// instances attach to the stdin/stdout which gets confusing.
childProcess.kill('SIGKILL');
}
if (process.platform === 'win32') {
// On Windows, launch the editor in a shell because spawn can only
// launch .exe files.
childProcess = spawn('cmd.exe', ['/C', editor].concat(args), {
stdio: 'inherit',
});
} else {
childProcess = spawn(editor, args, {stdio: 'inherit'});
}
childProcess.on('error', function() {});
childProcess.on('exit', function(errorCode) {
childProcess = null;
});
}
Example #18
Source File: http-bridge.js From loa-details with GNU General Public License v3.0 | 5 votes |
function spawnPacketCapturer(appSettings, serverPort) {
const args = ["--Port", serverPort];
if (appSettings?.general?.customLogPath !== null)
args.push("--CustomLogPath", appSettings?.general?.customLogPath);
if (appSettings?.general?.useWinpcap) args.push("--UseNpcap");
if (appSettings?.general?.server === "russia")
args.push("--Region", "Russia");
else if (appSettings?.general?.server === "korea")
args.push("--Region", "Korea");
try {
let binaryFolder;
if (process.env.DEBUGGING) {
binaryFolder = path.resolve(__dirname, "../../binary/");
} else {
binaryFolder = path.resolve("./binary/");
}
const binaryFiles = fs.readdirSync(binaryFolder);
for (const binaryFile of binaryFiles) {
if (binaryFile.endsWith(".exe")) {
packetCapturerProcess = spawn(
path.resolve(binaryFolder, binaryFile),
args
);
break;
}
}
log.info("Started Logger!");
} catch (e) {
log.error("Error while trying to open packet capturer: " + e);
dialog.showErrorBox(
"Error while trying to open packet capturer",
"Error: " + e.message
);
log.info("Exiting app...");
app.exit();
}
packetCapturerProcess.on("exit", function (code, signal) {
log.error(
`The connection to the Lost Ark Packet Capture was lost for some reason:\n
Code: ${code} and Signal: ${signal}`
);
dialog.showErrorBox(
"Error",
`The connection to the Lost Ark Packet Capture was lost for some reason:\n
Code: ${code} and Signal: ${signal}\n
Exiting app...`
);
log.info("Exiting app...");
app.exit();
});
}
Example #19
Source File: gulpfile.babel.js From Gentella-admin-Symfony-5 with MIT License | 5 votes |
function npmPublish(done) {
spawn('npm', ['publish'], { stdio: 'inherit' }).on('close', done);
}
Example #20
Source File: sandbox.js From riju with MIT License | 5 votes |
async function main() {
const sandboxScript = await fs.readFile("backend/sandbox.bash", "utf-8");
const lang = process.env.L;
if (!lang) {
die("environment variable unset: $L");
}
const langConfig = await readLangConfig(lang);
const uuid = getUUID();
console.log(`Starting session with UUID ${uuid}`);
const sessionArgs = privilegedSession({ uuid, lang });
const session = spawn(sessionArgs[0], sessionArgs.slice(1), {
stdio: ["ignore", "pipe", "inherit"],
});
let buffer = "";
await new Promise((resolve) => {
session.stdout.on("data", (data) => {
buffer += data.toString();
let idx;
while ((idx = buffer.indexOf("\n")) !== -1) {
const line = buffer.slice(0, idx);
buffer = buffer.slice(idx + 1);
if (line === "riju: container ready") {
resolve();
} else {
console.error(line);
}
}
});
});
const args = [].concat.apply(
["riju-pty", "-f"],
privilegedPty(
{ uuid },
bash(
`env L='${lang}' LANG_CONFIG=${quote(
JSON.stringify(langConfig)
)} bash --rcfile <(cat <<< ${quote(sandboxScript)})`
)
)
);
const proc = spawn(args[0], args.slice(1), {
stdio: "inherit",
});
try {
await new Promise((resolve, reject) => {
proc.on("error", reject);
proc.on("close", resolve);
});
} finally {
session.kill();
}
}
Example #21
Source File: cli.js From kit with MIT License | 5 votes |
spawn(node, [bin, ...args], {
stdio: 'inherit'
});
Example #22
Source File: serverAnalyzer.js From asymptoteWebApplication with GNU Lesser General Public License v3.0 | 5 votes |
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Resolver core function
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function asyRunManager(req, res, next, option) {
const asyArgs = ['-noV', '-outpipe', '2', '-noglobalread', '-f', option.outformat, option.codeFile];
const chProcOption = {
cwd: option.cwd,
}
const htmlFileExists = existsSync(req.body.htmlFile);
// if (req.body.reqType === "download" && option.outformat === "html" && htmlFileExists) {
// res.send({
// responseType: FLAGS.SUCCESS.ASY_OUTPUT_CREATED,
// isUpdated: !req.body.isUpdated
// });
// return;
// }
if (htmlFileExists) {
unlinkSync(req.body.htmlFile);
}
let stderrData = "", stdoutData = "";
const chProcHandler = spawn('asy', asyArgs, chProcOption);
setTimeout(() => {
chProcHandler.kill("SIGTERM");
}, serverTimeout)
// ------------------------------- onError
chProcHandler.on('error', (err) => {
const errResObject = errResCreator(FLAGS.FAILURE.PROCESS_SPAWN_ERR, err);
chProcHandler.kill();
res.send(errResObject);
});
// ------------------------------- onData
chProcHandler.stderr.on('data', (chunk) => {stderrData += chunk.toString()});
chProcHandler.stdout.on('data', (chunk) => {stdoutData += chunk.toString()});
// ------------------------------- onClose
chProcHandler.on('close', () => {});
// ------------------------------- onExit
chProcHandler.on('exit', (code, signal) => {
if (code === null) {
(signal === "SIGTERM") ? res.send(errResCreator(FLAGS.FAILURE.PROCESS_TIMEDOUT_ERR)) :
res.send(errResCreator(FLAGS.FAILURE.PROCESS_TERMINATED_ERR));
} else if (code !== 0) {
res.send({
...errResCreator(FLAGS.FAILURE.ASY_CODE_COMPILE_ERR),
stderr: stderrData,
stdout: stdoutData,
isUpdated: false
});
} else {
process.nextTick(() => {
const outputFilePath = req.body.usrAbsDirPath + "/" + req.body.codeFilename + "." + option.outformat;
if (existsSync(outputFilePath)) {
res.send({
responseType: FLAGS.SUCCESS.ASY_OUTPUT_CREATED,
stderr: stderrData,
stdout: stdoutData,
isUpdated: !req.body.isUpdated,
path: (option.outformat === "html")? req.body.usrRelDirPath
+ "/" + req.body.codeFilename + "." + option.outformat: ""
});
} else {
res.send({
responseType: FLAGS.SUCCESS.ASY_RUN_NO_OUTPUT,
stderr: stderrData,
stdout: stdoutData,
isUpdated: false
});
}
});
}
// console.log(`Code: ${code}\nSignal: ${signal}`);
});
}
Example #23
Source File: DiskUtils.js From HandyHost with GNU Lesser General Public License v2.1 | 4 votes |
getUSBFromDiskUtil(){
//macos
return new Promise((resolve,reject)=>{
const disksOut = [];
let out = '';
const diskutil = spawn('diskutil',['list']);
diskutil.stdout.on('data',d=>{
out += d.toString();
})
diskutil.stderr.on('data',d=>{
console.log('diskutil parsing error',d.toString());
})
const disks = [];
diskutil.on('close',()=>{
const lines = out.split('\n');
let disk = {};
let lineI = 0;
lines.map(line=>{
if(line.trim() == ''){
disks.push(disk);
disk = {};
lineI = 0;
}
else{
if(lineI == 0){
let parts = line.split(':')[0];
parts = parts.split('(');
parts[0] = parts[0].trim();
parts[1] = parts[1].replace(')','');
disk.path = parts[0];
disk.type = parts[1];
}
lineI++;
}
});
let jsonOut = ''
const jsonDiskList = spawn('bash',['./getUSB_MAC.sh'],{shell:true,env:process.env,cwd:process.env.PWD+'/aktAPI'})
jsonDiskList.stdout.on('data',d=>{
jsonOut += d.toString();
})
jsonDiskList.on('close',()=>{
//console.log('json list',jsonOut);
//console.log('disks',disks)
const json = JSON.parse(jsonOut);
const d2 = disks.filter(d=>{
return Object.keys(d).length > 0;
}).filter(disk=>{
console.log('f2',disk);
return disk.type.indexOf('external') >= 0 && disk.type.indexOf('physical') >= 0;
})
console.log('filtered disks',d2);
d2.map(disk=>{
let id = disk.path.split('/');
id = id[id.length-1];
console.log('disk to parse',disk,id);
let meta = json.AllDisksAndPartitions.find(d=>{
return d.DeviceIdentifier == id;
})
if(typeof meta.Partitions != "undefined" && typeof meta.MountPoint == "undefined"){
//ok find the right partition
let newMeta;
meta.Partitions.map(partition=>{
if(typeof partition.MountPoint != "undefined"){
newMeta = partition;
}
})
if(typeof newMeta != "undefined"){
console.log('using partition',newMeta,id);
meta = newMeta;
}
}
/*disksOut.push({
id:disk.path,
deviceIdentifier: meta.DeviceIdentifier,
mountPoint: meta.MountPoint,
size: meta.Size,
name: meta.VolumeName
})*/
disksOut.push({
meta:{
device: meta.MountPoint,
size: meta.Size,
model: meta.VolumeName,
path: disk.path
},
rm:true
})
})
//console.log('disks out',disksOut);
resolve(disksOut);
})
});
});
}