我在 node.js 中使用可以運行 shell 檔案的 express 和 hbs 撰寫了以下 Web 服務器,但是當我在 Web 瀏覽器中鍵入此 url 時,我不斷收到以下錯誤
這里的linux用戶名替換為我的linux用戶名
http://127.0.0.1:3000/run?file="/home/linux username here/nasServer/GameServers/minecraft/1.16.2 server/run.sh"
stderr: bash: <path to .sh file here>: No such file or directory.
child process exited with code 127.
nodejs檔案內容:
const express = require('express')
const hbs = require('hbs')
const app = express()
const port = 3000
// Set up handlebars engine
app.set('view engine', 'hbs')
app.get('/run', (req, res) => {
const { spawn } = require('child_process');
let callback = ""
ls = spawn("bash", [req.query.file])
ls.stdout.on('data', function (data) {
console.log('stdout: ' data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' data.toString());
});
ls.on('close', function (code) {
console.log('child process exited with code ' code.toString());
});
res.send({
out: callback
})
})
app.listen(port, () => {
console.log(`App listening on port ${port}`)
})
這是run.sh的內容:
#!/bin/bash
java -Xmx5G -jar /home/linux username here/nasServer/GameServers/minecraft/1.16.2\ server/spigot-1.16.2.jar nogui
uj5u.com熱心網友回復:
你好,我不知道為什么我決定嘗試解決這個問題,因為我只知道一點編碼(實際上只有腳本,哈哈),對 nodeJs 一無所知,但我在朋友 google 的幫助下測驗你的應用程式很有趣!
首先,因為我沒有你的 minecraft 檔案(jar 等),所以我只寫了一個小腳本“test.sh”,它只會回顯你的命令:
? cat test.sh
#!/bin/bash
echo "java -Xmx5G -jar /home/linux username here/nasServer/GameServers/minecraft/1.16.2\ server/spigot-1.16.2.jar nogui"
其次,經過 2 小時的培訓、修改、測驗,通過在您的應用程式中添加/洗掉內容以了解它是如何作業的,當我發現它適用于這個時,我終于回到了您的原始應用程式:
http://localhost:3000/run?file=test.sh
這是瀏覽器輸出(如預期的那樣):
{"out":""}
這是控制臺輸出:
? node 71963151.js
App listening on port 3000
stdout: java -Xmx5G -jar /home/linux username here/nasServer/GameServers/minecraft/1.16.2\ server/spigot-1.16.2.jar nogui
child process exited with code 0
事實是,當我們從查詢中洗掉雙引號時,它可以正常作業,但是當我像您嘗試做的那樣添加雙引號時:
http://localhost:3000/run?file="test.sh"
這是瀏覽器輸出(如預期的那樣):
{"out":""}
但這里是控制臺輸出:
? node 71963151.js
App listening on port 3000
stderr: bash: "test.sh": No such file or directory
child process exited with code 127
因此,總而言之,不要嘗試在瀏覽器上運行它:
http://127.0.0.1:3000/run?file="/home/<linux username here>/nasServer/GameServers/minecraft/<1.16.2 server>/run.sh"
試試這個:
http://127.0.0.1:3000/run?file=/home/<linux username here>/nasServer/GameServers/minecraft/<1.16.2 server>/run.sh
很多檔案幫助我理解了 nodejs 的作業方式,我喜歡這樣做:p 謝謝,你讓我想編碼!猜猜。
uj5u.com熱心網友回復:
我通過用 Unix 行結尾替換所有 windows 行結尾來解決問題,然后 bash 找到了 .sh 檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/462383.html
