我想编写一个JavaScript函数,它可以执行系统shell命令(例如
我该如何实现这个功能?
ls
)并返回结果值。我该如何实现这个功能?
ls
)并返回结果值。假设问者所说的“Shell Script”是指使用Node.js作为后端JavaScript,可能会使用commander.js框架来编写代码 :)
您可以使用来自node API的child_process模块。我在下面粘贴了示例代码。
var exec = require('child_process').exec;
exec('cat *.js bad_file | wc -l',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
我不知道为什么之前的答案都提供了各种复杂的解决方案。如果您只想执行像 ls
这样的快速命令,您不需要异步/等待或回调或任何其他东西。这就是您需要的全部内容 - execSync:
const execSync = require('child_process').execSync;
// import { execSync } from 'child_process'; // replace ^ if using ES modules
const output = execSync('ls', { encoding: 'utf-8' }); // the default is 'buffer'
console.log('Output was:\n', output);
为了进行错误处理,请在语句周围添加 try
/catch
块。
如果您正在运行需要很长时间才能完成的命令,则可以查看异步 exec
函数。
...几年后...
ES6已被接受为标准,ES7也即将到来,因此这篇文章值得更新。我们将使用ES6+async/await与nodejs+babel作为示例,前提是:
您的示例foo.js
文件可能如下所示:
import { exec } from 'child_process';
/**
* Execute simple shell command (async wrapper).
* @param {String} cmd
* @return {Object} { stdout: String, stderr: String }
*/
async function sh(cmd) {
return new Promise(function (resolve, reject) {
exec(cmd, (err, stdout, stderr) => {
if (err) {
reject(err);
} else {
resolve({ stdout, stderr });
}
});
});
}
async function main() {
let { stdout } = await sh('ls');
for (let line of stdout.split('\n')) {
console.log(`ls: ${line}`);
}
}
main();
确保您已安装Babel:
npm i babel-cli -g
安装最新预设:
npm i babel-preset-latest
通过以下方式运行:
babel-node --presets latest foo.js
var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");
简而言之:
// Instantiate the Shell object and invoke its execute method.
var oShell = new ActiveXObject("Shell.Application");
var commandtoRun = "C:\\Winnt\\Notepad.exe";
if (inputparms != "") {
var commandParms = document.Form1.filename.value;
}
// Invoke the execute method.
oShell.ShellExecute(commandtoRun, commandParms, "", "open", "1");
function exec(cmd, handler = function(error, stdout, stderr){console.log(stdout);if(error !== null){console.log(stderr)}})
{
const childfork = require('child_process');
return childfork.exec(cmd, handler);
}
这个函数可以轻松地使用,例如:
exec('echo test');
//output:
//test
exec('echo test', function(err, stdout){console.log(stdout+stdout+stdout)});
//output:
//testtesttest
使用NodeJS就像这样简单!如果你想在每次启动服务器时运行此脚本,可以查看forever-service应用程序!
var exec = require('child_process').exec;
exec('php main.php', function (error, stdOut, stdErr) {
// do what you want!
});
sudo mysql
,有什么办法吗?
这是可能的吗?
如果是,那么在执行此命令后,它将要求输入密码。 - Aman Deep这里是执行Linux的ifconfig
shell命令的简单命令。
var process = require('child_process');
process.exec('ifconfig',function (err,stdout,stderr) {
if (err) {
console.log("\n"+stderr);
} else {
console.log(stdout);
}
});
其中一个“主机”是Node.js,它有child_process模块。根据child_process文档,我们尝试使用以下代码执行Linux shell命令ps -aux,保存在runps.js中:注意:内置函数的示例包括parseInt和Math.exp。主机或实现可能提供其他未在本规范中描述的内置函数。
const { spawn } = require('child_process');
const ps = spawn('ps', ['-aux']);
ps.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ps.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ps.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
$ docker run --rm -v "$PWD":/usr/src/app -w /usr/src/app node:17-bullseye node ./runps.js
stdout: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.8 319312 33888 ? Ssl 11:08 0:00 node ./runps.js
root 13 0.0 0.0 6700 2844 ? R 11:08 0:00 ps -aux
child process exited with code 0
$ docker run --rm -u 7000 -v "$PWD":/usr/src/app -w /usr/src/app node:17-bullseye node ./runps.js
stdout: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
7000 1 5.0 0.8 319312 33812 ? Ssl 11:19 0:00 node ./runps.js
7000 13 0.0 0.0 6700 2832 ? R 11:19 0:00 ps -aux
child process exited with code 0
shell.js
的文件中:WScript.StdOut.WriteLine("Hallo, ECMAScript on Windows!");
WScript.CreateObject("WScript.Shell").run("C://Windows//system32//mspaint.exe");
cscript .\shell.js
Microsoft (R) Windows Script Host Version 5.812
Copyright (C) Microsoft Corporation. All rights reserved.
Hallo, ECMAScript on Windows!