简体   繁体   中英

nodejs for linux server programming / as scripting language

I am writing a script for provisioning new users for my application. Script will be written in node, as one of its tasks will be connecting to mysql to create new users in application's database.

I tried to use spawn-sync library (that surprisingly seems to be also async) to execute bash commands but every single one of them I need to do the following:

var spawnSync = require('spawn-sync');
var user_name = process.argv[2];

new Promise((resolve)=>{

    var result = spawnSync('useradd',[user_name]);
    if (result.status !== 0) {

        process.stderr.write(result.stderr);
        process.exit(result.status);

    } else {

        process.stdout.write(result.stdout);
        process.stderr.write(result.stderr);

    }

    resolve()

}).then(new Promise(function(resolve){

    // execute another part of script
    resolve()
})

Is there a better way of doing this? Whenever I try to look something up, all tutorials on the web seem to be talking only about express when it comes to the nodejs context.

Or perhaps you discourage using nodejs to be used as a scripting serverside laguage?

If you want to interact with processes synchronously, Node.js has that functionality built in via child_process.execSync() . Note that if the child process has a non-zero exit code it will throw (so you'll need to wrap it with a try/catch).

try {
  var cmd = ['useradd', user_name].join(' ');
  var stdout = require('child_process').execSync(cmd);
  console.log(stdout);
}
catch (e) {
  console.log(e);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM