• 首页
  • nodejs
  • node.js 调用 shelljs 接收 stdin 输入输出

node.js 调用 shelljs 接收 stdin 输入输出

input.png


文章目录


#node.js 调用 shell 脚本

现在能见到的有很多很多种方法

今天和大家分享的是 shelljs


shelljs 安装

npm install shelljs  --save


shelljs 使用 exec 方法

var shell = require("shelljs");

// exec 方法
shell.exec("echo hello  world!");


shelljs 使用全局模式

require('shelljs/global');

mkdir('-p', '/var/log');
cp('-R', '/var/log/*', '/home/zhangzhi/logs/');

cd('/home/zhangzhi/logs');

在shelljs 使用下,第一种方式必须使用 exec 方法,通过把 shell 脚本以参数形式传递给 exec 方法来运行即可.
在全局模式下,可以直接在 node.js 代码中书写 shell 脚本,比如上面的 mkdir ,cp ,cd 等等.


调用 shelljs 时如何输出标准流

var child = exec('ls', {async:true});
child.stdout.on('data', function(data) {
  /* ... do something with data ... */
  这里可以拦截标准输出流
});


调用 shelljs 时如何输入标准流

在linux 系统下创建一个系统用户,并且修改密码 (涉及到输入2次密码)
下面代码在 shelljs 全局模式下书写:

var userName='zhangzhi';
var password='pwd';

exec("adduser "+userName);
var child= exec("passwd " + userName,{async:true});
child.stdin.write(password+'\n'); //这里输入密码
child.stdin.write(password+'\n'); //这里输入确认密码
child.stdin.end();

出自:node.js 调用 shelljs 接收 stdin 输入输出

回到顶部