nodejs spawn example
Example 1: node spawn
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
Example 2: formidable nodejs example
// make this a middleware function,
// then put it on the route like you used jwt,
// then get the value with req.users.
const { IncomingForm } = require('formidable')
const { resolve } = require('path')
const { existsSync, writeFileSync } = require('fs')
module.exports = (req, res, next) => {
const form = new IncomingForm({
maxFileSize: 1 * 1024 * 1024,
keepExtensions: true
})
form.parse(req, (error, fields, file) => {
if (error) return next(error)
const patternFile = /\.(jpg|jpeg|png|svg|gif|raw|webp)$/gi.test(file.productImage.name)
if (patternFile) {
const pathFile = resolve(process.cwd(), 'servers/uploads/', file.productImage.name)
const fileExits = existsSync(pathFile)
if (!fileExits) {
writeFileSync(pathFile)
req.users = JSON.parse(JSON.stringify({ fields, file }))
return next()
}
req.users = JSON.parse(JSON.stringify({ fields, file }))
return next()
}
})
}
Example 3: nodejs cluster example
import http, { Server } from 'http'
import cluster, { Worker } from 'cluster'
import { cpus, CpuInfo } from 'os'
import consola from 'consola'
import chalk from 'chalk'
import app from './src/app'
const coreThread: CpuInfo[] = cpus()
if (cluster.isMaster) {
for (let i = 0; i < coreThread.length; i++) {
cluster.fork()
}
const workersTread: any = []
for (const id in cluster.workers) {
workersTread.push(id)
}
workersTread.forEach(
async (pid: number, _: number): Promise<void> => {
await cluster.workers[pid].send({
from: 'isMaster',
type: 'SIGKILL',
message: 'cleanup is worker dead and change to new worker'
})
}
)
if (process.env.NODE_ENV !== 'production') {
cluster.on('online', (worker: Worker): void => {
if (worker.isConnected()) {
console.info(`${chalk.greenBright('worker active pid')}: ${worker.process.pid}`)
}
})
cluster.on('exit', (worker: Worker, code: number, signal: string): void => {
if (worker.isDead()) {
console.info(`${chalk.redBright('worker dead pid')}: ${worker.process.pid}`)
}
cluster.fork()
})
}
} else {
const server = http.createServer(app) as Server
const host: any = process.env.HOST
const port: any = process.env.PORT
server.listen(port, host, (): void => consola.success(`server is running on ${port}`))
}
Example 4: how to return when child process is complete in node js
var execSync = require('exec-sync');
var user = execSync('python celulas.py');