zoukankan      html  css  js  c++  java
  • Node child_process Study.2

    child_process 模块用于新建子进程。子进程的运行结果存储在系统缓存之中,等到子进程运行结束之后,主进程再用回调函数读取子进程的运行结果

    1.exec()

      exec 方法用于执行base命令,它的参数是一个命令字符串

      

    var exec = require('child_process').exec;
    
    var ls = exec('ls -l', function() {
         if (error) {
            console.log(error.stack);
            console.log('error code:' + error.node);  
        } 
         console.log('child Process STDOUT:' + stdout)
    })    
    

    上面代码的exec方法用于新建一个子进程,然后缓存它的运行结果,运行结束后调用回调函数。

    exec方法最多可以接受两个参数,第一个参数是所要执行的shell命令,第二个参数是回调函数,该函数接受三个参数,分别是发生的错误、标准输出的显示结果、标准错误的显示结果。

    由于标准输出和标准错误都是流对象(stream),可以监听data事件,因此上面的代码也可以写成下面这样

    var exec = require('child_process').exec;
    var child = exec('ls -l');
    
    child.stdout.on('data', function(data) {
       console.log('stdout', data) ;
    })
    
    child.stderr.on('data', function (data) {
       console.log('stdout', data) ;
    })
    
    child.on('close', function(code) {
       console.log('closing code', code); 
    })
    

      上面的代码标明,子进程本身有close事件,可以设置回调函数。

      上面的代码还有一个好处,监听data事件之后,可以实时输出结果,否则只有等待子进程结束,才会输出结果,所以,

    如果子进程运行时间较长,或者是持续运行,第二种写法更好

    下面是另一个例子,假定有一个child.js文件

      

    var exec = require('child_process').exec;
    
    exec('node -v', function(error, stdout, stderr) {
       console.log('stdout:', stdout);
        console.log('stderr', srderr);
        if (error !== null) {
            console.log('exec error', error); 
        }   
    })

    运行后,该文件的输出结果如下:

    $node child.js

    stdout : v0.11.14

    stderr: 

    exec方法会直接调用bash(/bin/sh程序)来解释命令,所以如果用用户输入的参数,exec方法是不安全的

    切记: 在用用户输入的情况相爱,最好不适用exec方法,而是是哟名execFile方法。

    2.execSync()

      execSync是exec的同步执行版本

    3.execFile方法直接执行特定的程序,参数作为数组传入,不会被bash解释,因此具有较高的安全性

      

    var child_process = require('child_process');
    
    var path = '.';
    child_process.execFile('/bin/ls', ['-l', path], function(err, result) {
        console.log(result);
    })

    上面代码中,假定path来自用户输入,如果其中包含了分好或者反引号,ls程序不理解他们的含义,因此也就

      

      

  • 相关阅读:
    CentOS7-samba文件共享服务
    centos7-vsftpd文件服务器
    linux用户和权限管理
    linux程序安装及包管理
    linux文件查找-find命令
    linux文本编辑器-VIM基本使用方法
    linux文本处理工具及正则表达式
    linux目录结构及文件管理
    linux基本命令及使用方法
    巴什博奕----取完者负的分析
  • 原文地址:https://www.cnblogs.com/jintaostudy/p/8311536.html
Copyright © 2011-2022 走看看