53 lines
1.2 KiB
JavaScript
53 lines
1.2 KiB
JavaScript
import fs from 'node:fs';
|
|
import fsp from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import process from 'node:process';
|
|
import { spawn } from 'node:child_process';
|
|
|
|
const [, , logPath, ...commandArgs] = process.argv;
|
|
|
|
if (!logPath || commandArgs.length === 0) {
|
|
process.stderr.write('Usage: node docker/run-with-log-file.mjs <log-path> <command> [args...]\n');
|
|
process.exit(1);
|
|
}
|
|
|
|
await fsp.mkdir(path.dirname(logPath), { recursive: true });
|
|
|
|
const logStream = fs.createWriteStream(logPath, { flags: 'a' });
|
|
const child = spawn(commandArgs[0], commandArgs.slice(1), {
|
|
cwd: process.cwd(),
|
|
env: process.env,
|
|
stdio: ['inherit', 'pipe', 'pipe']
|
|
});
|
|
|
|
function writeChunk(target, chunk) {
|
|
target.write(chunk);
|
|
logStream.write(chunk);
|
|
}
|
|
|
|
child.stdout.on('data', (chunk) => {
|
|
writeChunk(process.stdout, chunk);
|
|
});
|
|
|
|
child.stderr.on('data', (chunk) => {
|
|
writeChunk(process.stderr, chunk);
|
|
});
|
|
|
|
child.on('error', (error) => {
|
|
const message = `${error.stack || error.message}\n`;
|
|
writeChunk(process.stderr, message);
|
|
logStream.end(() => {
|
|
process.exit(1);
|
|
});
|
|
});
|
|
|
|
child.on('close', (code, signal) => {
|
|
logStream.end(() => {
|
|
if (signal) {
|
|
process.kill(process.pid, signal);
|
|
return;
|
|
}
|
|
|
|
process.exit(code ?? 1);
|
|
});
|
|
});
|