Node.JS學習筆記(10)_環境變數配置
npm install dotenv --save
在專案所在根目錄下產生.env檔案
用nano編輯器編寫以下環境變數
HOST=localhost
PORT=3000
const http = require('http');
require('dotenv').config();
// Read the host address and the port from the environment
const hostname = process.env.HOST;
const port = process.env.PORT;
// Return JSON regardless of HTTP method or route our web app is reached by
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(`{"message": "Hello World"}`);
});
// Start a TCP server listening for connections on the given port and host
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
留言
張貼留言