javascript-scripting-tool/scripting.js

71 lines
1.8 KiB
JavaScript

#!/usr/bin/node
const jssVersion = [1, 0, 0];
const jssVersionString = jssVersion.join(".");
const fs = require('fs');
const execSync = require('child_process').execSync;
const spawn = require('child_process').spawn;
async function bash(bashScript, options) {
var bashArgs = [];
if (options !== undefined) {
if (options.strict === true) {
bashArgs.push("-e");
}
}
bashArgs.push("-");
var child = spawn("bash", bashArgs);
child.stdin.setEncoding('utf-8');
child.stdin.write(bashScript);
child.stdin.end();
let data = "";
for await (const chunk of child.stdout) {
data += chunk;
}
let error = "";
for await (const chunk of child.stderr) {
error += chunk;
}
const exitCode = await new Promise((resolve, reject) => child.on('close', resolve));
if (exitCode) {
throw new Error( `subprocess error exit ${exitCode}, ${error}`);
}
return data;
}
function exec(text) {
return execSync(text)+'';
}
function print(...text) {
process.stdout.write(text.join(" "));
}
function println(...text) {
print(text);
process.stdout.write("\n");
}
const scriptPath = process.argv[2];
const args = process.argv.splice(3);
const rawScriptContent = fs.readFileSync(scriptPath)+'';
const fixedScriptContent = rawScriptContent.substring(rawScriptContent.indexOf("\n") + 1);
const scriptPrefix = `async () => {`;
const scriptSuffix = `}`;
var evaluatedScript = eval(scriptPrefix + fixedScriptContent + scriptSuffix);
// Cleanup variables
delete spawn;
delete fs;
delete execSync;
delete scriptPath;
delete rawScriptContent;
delete fixedScriptContent;
delete scriptPrefix;
delete scriptSuffix;
evaluatedScript();