Add 'scripting.js'

This commit is contained in:
andreacavalli 2020-03-19 00:31:37 +01:00
parent 15f0e9db7b
commit d3f16d3bfe

66
scripting.js Normal file
View File

@ -0,0 +1,66 @@
#!/usr/bin/node
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);
}
function println(text) {
process.stdout.write(text + '\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();