Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/backend/bash.ts
1447 views
1
/*
2
Easily spawn a bash script given by a string, which is written to a temp file
3
that is automatically removed on exit. Returns a child process.
4
*/
5
6
import { chmod, mkdtemp, writeFile } from "node:fs/promises";
7
import { tmpdir } from "node:os";
8
import { ChildProcessWithoutNullStreams, spawn } from "node:child_process";
9
import { cleanUpTempDir } from "./execute-code";
10
import { join } from "node:path";
11
//import getLogger from "@cocalc/backend/logger";
12
//const logger = getLogger("bash");
13
14
export default async function bash(
15
command: string,
16
spawnOptions?,
17
): Promise<ChildProcessWithoutNullStreams> {
18
let tempDir = "";
19
let tempPath = "";
20
try {
21
tempDir = await mkdtemp(join(tmpdir(), "cocalc-"));
22
tempPath = join(tempDir, "a.sh");
23
//logger.debug("bash:writing temp file that contains bash program:\n", command);
24
await writeFile(tempPath, command);
25
await chmod(tempPath, 0o700);
26
} catch (err) {
27
await cleanUpTempDir(tempDir);
28
throw err;
29
}
30
//logger.debug(`spawning bash program: ${JSON.stringify(command).slice(0,1000)}...`);
31
const child = spawn("bash", [tempPath], spawnOptions);
32
child.once("exit", async () => {
33
await cleanUpTempDir(tempDir);
34
});
35
return child;
36
}
37
38