4

I am trying to use child process in nodejs to launch a tomcat server on local machine. It is am experiment that will help me understand the way child process works and will help with a project I am working on. I've been looking at the documentation here: http://nodejs.org/api/child_process.html but I am having a little of an issue actually doing this.

What I am trying to do is to run nodejs somewhere locally, once I click somewhere (or even launch the page), the page should run a tomcat server, make sure it is up then load the localhost:8080 welcome page. Once I close the page here the nodejs APIs are being called, it should shutdown tomcat (this part is not necessary for now, but just part of the experiment). Thanks!

4

1 回答 1

2

看看这个 npm 模块Shelljs

ShellJS - 用于 Node.js 构建状态的 Unix shell 命令

ShellJS 是基于 Node.js API 的 Unix shell 命令的可移植(Windows/Linux/OS X)实现。您可以使用它来消除您的 shell 脚本对 Unix 的依赖,同时仍保留其熟悉且强大的命令。你也可以全局安装它,这样你就可以从外部节点项目运行它——告别那些粗糙的 Bash 脚本!

ShellJS 已经在许多相关项目中进行了测试

既然它可以调用脚本,那么你就可以控制Tomcat的启动和关闭脚本,继续你的实验:)

ShellJS 可以选择:

执行(命令 [,选项] [,回调])

可用选项(默认全部为 false):

async: Asynchronous execution. Defaults to true if a callback is provided.
silent: Do not echo program output to console.

例子:

var version = exec('node --version', {silent:true}).output;

var child = exec('some_long_running_process', {async:true}); child.stdout.on('data', function(data) { /* ... 对数据做一些事情 ... */ });

exec('some_long_running_process', function(code, output) {
console.log('Exit code:', code); console.log('Program output:', output); });

除非另有说明,否则同步执行给定的命令。在同步模式下返回对象 { code:..., output:... },包含程序的输出 (stdout + stderr) 及其退出代码。否则返回子进程对象,回调获取参数(代码、输出)。

注意:对于长期存在的进程,最好异步运行 exec(),因为当前的同步实现会占用大量 CPU。这应该很快得到解决。

于 2013-03-09T02:11:04.750 回答