Sun*_*hoo 108 javascript
我想编写一个JavaScript函数,它将执行系统shell命令(ls
例如)并返回值.
我该如何实现这一目标?
Jos*_*osh 119
这里的许多其他答案似乎都是从浏览器中运行的JavaScript函数的角度来解决这个问题.我会拍摄并回答,假设当提问者说"Shell Script"时,他的意思是Node.js后端JavaScript.可能使用commander.js来使用框架你的代码:)
您可以使用节点API中的child_proccess模块.我粘贴了下面的示例代码.
var exec = require('child_process').exec, child;
child = 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);
}
});
child();
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
Mir*_*sin 38
......几年后......
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();
Run Code Online (Sandbox Code Playgroud)
确保你有巴贝尔:
npm i babel-cli -g
Run Code Online (Sandbox Code Playgroud)
安装最新预设:
npm i babel-preset-latest
Run Code Online (Sandbox Code Playgroud)
运行它:
babel-node --presets latest foo.js
Run Code Online (Sandbox Code Playgroud)
Dan*_*scu 26
我不知道为什么之前的答案给出了各种复杂的解决方案.如果你只想执行类似的快速命令ls
,则不需要async/await或callbacks或任何东西.这就是你需要的全部 - 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);
Run Code Online (Sandbox Code Playgroud)
对于错误处理,请在语句周围添加try
/ catch
块.
如果您正在运行需要很长时间才能完成的命令,那么请查看异步exec
函数.
Mat*_*att 17
这完全取决于JavaScript环境.请详细说明.
例如,在Windows Scripting中,您执行以下操作:
var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");
Run Code Online (Sandbox Code Playgroud)
Dan*_*ana 14
简而言之:
// 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");
Run Code Online (Sandbox Code Playgroud)
小智 7
NodeJS很简单!如果您想在服务器的每次启动时运行此脚本,您可以查看永久服务应用程序!
var exec = require('child_process').exec;
exec('php main.php', function (error, stdOut, stdErr) {
// do what you want!
});
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
这个函数可以很容易地使用,例如:
exec('echo test');
//output:
//test
exec('echo test', function(err, stdout){console.log(stdout+stdout+stdout)});
//output:
//testtesttest
Run Code Online (Sandbox Code Playgroud)
注意:这些答案是从基于浏览器的客户端到基于Unix的Web服务器。
在客户端上运行命令
您基本上不能。安全性说只能在浏览器中运行,并且它对命令和文件系统的访问受到限制。
在服务器上运行ls
您可以使用AJAX调用来检索通过GET传递参数的动态页面。
请注意,这还会带来安全风险,因为您必须做一些事情以确保rouge hacker先生不会让您的应用程序运行:/ dev / null && rm -rf / ......
因此,总的来说,从JS运行只是一个不好的主意。
这是执行ifconfig
Linux shell命令的简单命令
var process = require('child_process');
process.exec('ifconfig',function (err,stdout,stderr) {
if (err) {
console.log("\n"+stderr);
} else {
console.log(stdout);
}
});
Run Code Online (Sandbox Code Playgroud)