一、shell腳本調(diào)用js腳本绩鸣,以及傳參
1怀大、js代碼
// 打印所有參數(shù)
console.log('打印所有參數(shù):');
process.argv.forEach((index, value) => console.log(index, value));
// 獲取傳遞的參數(shù)
var cp1 = process.argv[2];
var cp2 = process.argv[3];
console.log('打印傳遞的參數(shù): ' + cp1 + ' ' + cp2);
2、shell代碼
appid="id123"
appname="小程序"
# 執(zhí)行js并傳參數(shù)
node miniprogram.js $appid $appname
3呀闻、調(diào)用shell腳本叉寂,將shell中參數(shù)傳遞給js
sh test.sh
4、打印傳遞的參數(shù)
└─[0] <git:(master?) > sh test.sh
這是 miniprogram.js
打印所有參數(shù):
/usr/local/bin/node 0
/Users/wxq/Desktop/testjs/miniprogram.js 1
id123 2
小程序 3
打印傳遞的參數(shù): id123 小程序
在這里可以看到所需的參數(shù)值位于索引2和3上总珠。
二屏鳍、js腳本調(diào)用shell腳本,以及傳參
1局服、js代碼
// Nodejs下引入模塊child_process實(shí)現(xiàn)調(diào)用shell
var child = require('child_process');
let appid = 'id123'
let appname = "小程序"
let command = 'bash ./test.sh ' + appid + ' ' + appname
// 調(diào)用shell腳本并傳參數(shù)
child.exec(command, function(err, sto) {
// sto才是真正的輸出
console.log('sto: ' + sto);
})
2钓瞭、shell代碼
echo "從js中獲取的參數(shù)為:$1 $2"
3、調(diào)用js腳本淫奔,將js中參數(shù)傳遞給shell
node miniprogram.js
4山涡、打印傳遞的參數(shù)
└─[0] <git:(master?) > node miniprogram.js
sto: 從js中獲取的參數(shù)為:id123 小程序
三、js腳本中調(diào)用終端命令
let command1 = 'ls'
let command2 = '/usr/local/bin'
let command3 = 'git pull'
let command4 = 'npm list'
let command5 = 'node -v'
import shell from 'shelljs'
shell.exec('pwd')
shell.exec(command1)
shell.exec('open ' + command2)
shell.exec(`open "${command2}"`)
shell.exec(command3)
shell.exec(command4)
shell.exec(command5)
Demo地址:js-shell-intercall