• NodeJS > exécuter du shell code

      Possibly using commander.js to use frame your code : You could use the child_proccess module from node’s API :

       

      var exec = require('child_process').exec, child;
      
      child = exec('cat *.js bad_file | wc -l',
         function (error, stdout, stderr) {
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            if (error !== null) {
               console.log('exec error: ' + error);
            }
         });
      child();

       

      Except for one thing. You’ll get the error "child is not a function". The call to exec() executes the command - no need to call child(). Unfortunately, the callback isn’t called whenever the child process has something to output - it is called only when the child process exits. Sometimes that’s OK and sometimes it’s not

       

      To avoid callbacks, you can use execSync.

       

      ES6 has been accepted as a standard and ES7 is around the corner so it deserves updated answer. We’ll use ES6+async/await with nodejs+babel as an example, prerequisites are:

       

      nodejs with npm

       

      babel

       

      Your example foo.js file may look like:

       

      import { exec } from 'child_process';
      
      /**
       * Execute simple shell command (async wrapper).
       * @param {String} cmd
       * @return {Object} { stdout: String, stderr: String }
       */
      async function sh(cmd) {
        return new Promise(function (resolve, reject) {
          exec(cmd, (err, stdout, stderr) => {
            if (err) {
              reject(err);
            } else {
              resolve({ stdout, stderr });
            }
          });
        });
      }
      
      async function main() {
         let { stdout } = await sh('ls');
         for (let line of stdout.split('\n')) {
            console.log(`ls: ${line}`);
         }
      }
      
      main();

       

      Make sure you have babel:

       

      npm i babel-cli -g

       

      Install latest preset:

       

      npm i babel-preset-latest

       

      Run it via:

       

      babel-node --presets latest foo.js

       

      If you only need to execute a quick command, all the async/await is overkill. You can just use execSync

       

      In a nutshell:

       

      // Instantiate the Shell object and invoke its execute method.
      var oShell = new ActiveXObject("Shell.Application");
      
      var commandtoRun = "C:\\Winnt\\Notepad.exe";
      if (inputparms != "") {
        var commandParms = document.Form1.filename.value;
      }
      
      // Invoke the execute method.
      oShell.ShellExecute(commandtoRun, commandParms, "", "open", "1");

       

      Just for info phpied.com/javascript-shell-scripting – Eduplessis Oct 21 ’15 at 1:37

       

      There seems to be a lot of hand-wringing over which web browser this is running in, but folks should realize that JavaScript is also a perfectly valid Windows shell scripting language. – Craig Feb 3 ’16 at 0:48

       

      With NodeJS is simple like that! And if you want to run this script at each boot of your server, you can have a look on the forever-service application!

       

      var exec = require('child_process').exec;
      
      exec('php main.php', function (error, stdOut, stdErr) {
          // do what you want!
      });

       

      To avoid callbacks, for quick commands you can use execSync.

       

      I don’t know why the previous answers gave all sorts of complicated solutions. If you just want to execute a quick command like ls, you don’t need async/await or callbacks or anything. Here’s all you need - execSync:

       

      const execSync = require('child_process').execSync;
      // import { execSync } from 'child_process';  // replace ^ if using ES modules
      const output = execSync('ls', { encoding: 'utf-8' });  // the default is 'buffer'
      console.log('Output was:\n', output);

       

      For error handling, add a try/catch block around the statement.

       

      If you’re running a command that takes a long time to complete, then yes, look at the asynchronous exec function.

      With nashorn you can write a script like this:

       

      $EXEC('find -type f');
      var files = $OUT.split('\n');
      files.forEach(...
      ...

       

      and run it:

       

      jjs -scripting each_file.js

       

      Here is simple command that executes ifconfig shell command of Linux

       

      var process = require('child_process');
      process.exec('ifconfig',function (err,stdout,stderr) {
          if (err) {
              console.log("\n"+stderr);
          } else {
              console.log(stdout);
          }
      });

       

      vim command.js

       

      copy n past this

       

      #!/usr/bin/env node
      function execute(command) {
        const exec = require('child_process').exec
      
        exec(command, (err, stdout, stderr) => {
          process.stdout.write(stdout)
        })
      }
      
      execute('echo "Hello World!"')

       

      node command.js

 

Aucun commentaire

 

Laissez un commentaire