NodeJs Shell(下)
2016-10-14 本文已影响145人
卖梦想的男孩
学会了脚本的基本知识,学习使用命令行调用系统命令,增强脚本的实际能力。
脚本可以通过 child_process 模块新建子进程,从而执行 Unix 系统命令。
简单脚本
- 创建脚本
#!/usr/bin/env node
var name = process.argv[2];
var exec = require('child_process').exec;
var child = exec('echo hello ' + name, function(err, stdout, stderr) {
if (err) throw err;
console.log(stdout);
});
- 执行脚本,查看调用系统echo命令的结果
扩展脚本
shelljs 模块重新包装了 child_process,调用系统命令更加方便。
- 安装shelljs
npm install --save shelljs
- 编写脚本
#!/usr/bin/env node
var name = process.argv[2];
var shell = require("shelljs");
shell.exec("echo hello " + name);
- 运行查看结果
进一步扩展脚本
shelljs中有个global.js,里面封装了常用的系统命令
- 编写脚本
require('shelljs/global');
if(!which('ping')){
echo('not found ping !');
exit(1);
}
cd('~/Desktop')
mkdir('nodejs_temp')
if(exec('ping www.xxx.com').code !== 0){
echo('ping error!');
exit(1);
}
```
- 执行脚本,并发现桌面存在一个nodejs_temp文件夹