I had the need to serve an HTML page from a Node.js server, and this is the simplest code that does the trick:
我需要从Node.js服务器提供HTML页面,而这是解决问题的最简单的代码:
const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/html' })
fs.createReadStream('index.html').pipe(res)
})
server.listen(process.env.PORT || 3000)
No dependencies needed.
无需依赖。
Add this to an app.js
file, then create an index.html
page, and run node app.js
将此添加到一个app.js
文件,然后创建一个index.html
页面,并运行node app.js
Notice that the above code does not provide support for serving static assets, it will just serve the index.html
page.
请注意,上面的代码不提供服务静态资产的支持,它将仅服务index.html
页面。