问题
when running node in command over a specific port, I'd start the app this way:
PORT=1234 node app.js
how do I pass the port to the forever
command? no matter what I try, it seems to not want to work.
I've tried:
- passing the port as an arg:
forever start app.js 1234
- passing the port declaration as an arg:
forever start app.js PORT=1234
回答1:
PORT=1234 forever start app.js
回答2:
You can try adding export PORT=1234
to app.js
Then just run with forever start app.js
回答3:
If you are using Node forever, you can create a forever.json file in your root directory and mention all your ports there in that json file inside an array. Example:
forever.json
[
{
"uid": "app1",
"append": true,
"watch": true,
"script": "server.js",
"sourceDir": "D:\\DEVELOPEMENT\\workshop",
"args": ["--port", "8081", "--ip", "127.0.0.1"]
},
{
"uid": "app2",
"append": true,
"watch": true,
"script": "server.js",
"sourceDir": "D:\\DEVELOPEMENT\\workshop" ,
"args": ["--port", "8082", "--ip", "127.0.0.1"]
},
{
"uid": "app3",
"append": true,
"watch": true,
"script": "server.js",
"sourceDir": "D:\\DEVELOPEMENT\\workshop" ,
"args": ["--port", "8083", "--ip", "127.0.0.1"]
}
]
Provide your source directory and script(app.js/server.js).
Now run all the above 3 apps in different ports by command forever start forever.json
But node forever pass ip and ports through command line to our program. So to get values from process.argv we need minimist package of node. install minimist and then write your app.js as below to provide ip and port dynamically through command(Forever will do it automatically).
server.js / app.js
var express = require('express');
var app = express();
const parseArgs = require('minimist') (process.argv.slice(2))
const IP = parseArgs.ip || "127.0.0.1"
const PORT = parseArgs.port || 8000
app.get("/", function (req, res) {
res.send("Server running on " + IP + ":" + PORT)
})
console.log("START ", IP+" :",PORT)
app.listen(PORT, IP)
module.exports = app;
Now run forever start forever.json and check all the port described in forever.json.
来源:https://stackoverflow.com/questions/32132731/starting-node-forever-script-with-port-xxxx