发布于 2015-08-18 00:28:59 | 563 次阅读 | 评论: 0 | 来源: PHPERZ

Child Process模块

通过Child Process模块,我们能创建子进程,借助 stdin、 stdout、 stderr来实现进程间通信(很C++)。使用子进程能够做很多事情,如打印、发邮件、调用脚本或其他程序(不局限于javascript)。

要使用Child Process模块,我们需要在代码中添加 require("child_process")。

以下内容缺乏文档支持,并未经过充分测试,可能存在一定的理解偏差。这部分功能是极有用的,希望在项目中使用的时候注意测试。

Child Process模块本身应该也并完全开发完全。 spawn()、 execFile()可用, exec()和 fork()尚未实现。

  1. spawn(command, [args], [options])
    最基本的创建进程的方法。前两个参数比较重要,例如现在想从phantom进程中运行一段nodejs脚本,脚本路径为 “main.js”,这个脚本接受一个参数,假定为 “helloworld”,那么如果想得到这段脚本的运行结果应该怎么做呢?参考下面的脚本:
    var spawn = require("child_process").spawn;
    child = spawn('node', ['main.js', 'helloworld']);
    child.stdout.on("data", function (data) {
        console.log("spawnSTDOUT:", JSON.stringify(data))
    });
    child.stderr.on("data", function (data) {
        console.log("spawnSTDERR:", JSON.stringify(data))
    });
    child.on("exit", function (code) {
        console.log("spawnEXIT:", code)
    });
    setTimeout(function () {
        phantom.exit(0)
    }, 2000);
    其 实 spawn()方法没什么神秘的,它就是运行第一个参数表示的命令,第二个参数就是这个命令的参数列表。所以如果要开启一个新的phantom进程,第一 个参数为 phantom就行。同样的道理,指定好程序的路径或者是脚本语言解释器的路径,通过这个方法可以做的事情很多。
    比较不方便的是,进程间的通信只能通过 stdin、 stdout、 stderr来完成,调用 spawn()方法后,还需要对这些交互信息进行监听,上面的例子中演示了监听 stdout和 stderr的方法。
  2. execFile(cmd, args, opts, cb)
    就像刚刚说的, spawn()方法稍微感觉有点麻烦,使用 execFile()能够稍稍简化上面的代码。 execFile()的前三个参数与 spawn()的三个参数完全一样,不同的是它多了一个 cb回调函数,看一个例子就知道这个回调函数有什么用了:
    var execFile = require("child_process").execFile;
    child = execFile('node', ['main.js', 'helloworld'], null,
        function (err, stdout, stderr) {
            console.log("execFileSTDOUT:", JSON.stringify(stdout))
            console.log("execFileSTDERR:", JSON.stringify(stderr))
        });
    setTimeout(function () {
        phantom.exit(0)
    }, 2000);
    在 execFile()中,对 stdout、 stderr的监听做了封装,简化了我们的代码,不过功能上与 spawn()并无区别。
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务