├── test.sh
├── demo_node.js
test.sh
内容
#!/bin/bash
echo '这是测试'
demo_node.js
内容
let express = require('express');
let router = express.Router();
const child_process = require('child_process');
router.post('/', function (req, res, next) {
child_process.execFile('./test.sh',null,null, function (error, stdout, stderr) {
console.log('execFile', stdout, error);
});
res.sendStatus(200)
});
module.exports = router;
使用postman请求可以看到以下错误
> node ./bin/www
execFile { Error: spawn ./test.sh ENOENT
at exports._errnoException (util.js:1016:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:189:19)
at onErrorNT (internal/child_process.js:366:16)
at _combinedTickCallback (internal/process/next_tick.js:102:11)
at process._tickCallback (internal/process/next_tick.js:161:9)
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn ./test.sh',
path: './test.sh',
spawnargs: [],
cmd: './test.sh' }
按照官网的文档按道理是没错的
上面的提示的意思是没找到文件的路径或者没有权限
解决方案
var path = require('path');
...
router.post('/', function (req, res, next) {
var exePath = path.resolve(__dirname, './test.sh');
child_process.execFile(exePath,null,null, function (error, stdout, stderr) {
console.log('execFile', stdout, error);
});
res.sendStatus(200)
});
再执行发现又报错了
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1>spawn EACCES</h1>
<h2></h2>
<pre>Error: spawn EACCES
at exports._errnoException (util.js:1016:11)
at ChildProcess.spawn (internal/child_process.js:317:11)
at exports.spawn (child_process.js:491:9)
at Object.exports.execFile (child_process.js:208:15)
at /Users/fangshufeng/Desktop/ThirdLib/NodeServe/NodeServersTest/routes/account.js:28:19
at Layer.handle [as handle_request] (/Users/fangshufeng/Desktop/ThirdLib/NodeServe/NodeServersTest/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/fangshufeng/Desktop/ThirdLib/NodeServe/NodeServersTest/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/fangshufeng/Desktop/ThirdLib/NodeServe/NodeServersTest/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/fangshufeng/Desktop/ThirdLib/NodeServe/NodeServersTest/node_modules/express/lib/router/layer.js:95:5)
at /Users/fangshufeng/Desktop/ThirdLib/NodeServe/NodeServersTest/node_modules/express/lib/router/index.js:281:22</pre>
</body>
</html>
提示来看是没有权限,查看test.sh的权限
➜ routes git:(master) ✗ ll test.sh
-rw-r--r-- 1 fangshufeng staff 32B Mar 19 14:57 test.sh
➜ routes git:(master) ✗
发现没有执行权限,修改权限,这里通过数字法修改,不熟悉的可看该篇文章
chmod 777 test.sh
➜ routes git:(master) ✗ ll test.sh
-rwxrwxrwx 1 fangshufeng staff 32B Mar 19 14:57 test.sh
再请求发现好了
POST /demo_node 200 12.843 ms - 2
execFile 这是测试
网友评论