Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
benri.ts
import {
exec,
spawn,
SpawnOptionsWithoutStdio,
} from 'child_process'
import { createInterface } from 'readline'
import { promisify } from 'util'
process.stdin.setEncoding('utf8')
export const execAsync = promisify(exec)
export const spawnAsync = async (command: string, option?: SpawnOptionsWithoutStdio) => new Promise((resolve, reject) => {
const _process = spawn(command, option)
if (_process.stdout === null) {
return reject(new Error('stdout is not defined'))
}
if (_process.stderr === null) {
return reject(new Error('stderr is not defined'))
}
_process.stderr.pipe(process.stderr)
_process.stdout.pipe(process.stdout)
_process.on('error', (err) => {
return reject(err)
})
_process.on('disconnect', () => {
return reject(new Error('disconnected'))
})
_process.on('message', (message) => {
console.log(message)
})
_process.on('exit', (code) => {
return resolve(code)
})
_process.on('close', (code) => {
return resolve(code)
})
})
export const scan = async (): Promise<string> => {
const _buffers = []
for await (const chunk of process.stdin) {
_buffers.push(chunk)
}
const buffer = Buffer.concat(_buffers)
return buffer.toString()
}
export const scan_ = async (): Promise<string[]> => new Promise((resolve) => {
const lines: string[] = []
const reader = createInterface({
input: process.stdin,
})
reader.on('line', (line) => {
lines.push(line)
})
reader.on('close', () => {
resolve(lines)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment