【发布时间】:2017-03-14 18:27:04
【问题描述】:
我想读取一个 HTML 文件。
我的 HTML 内容:
<html>
<hear>
<title>Learn NodeJS</title>
</head>
<body>
<center>
<h1>Learn NodeJS with Khuong Pham</h1>
<img width="400" src="/nodejs.png" />
</center>
</body>
</html>
我试过了:
const http = require('http')
const fs = require('fs')
const express = require('express')
const app = express()
const folderPath = __dirname + '/public_files'
app.use(express.static(folderPath))
http.createServer(function(request, response) {
var filePath = folderPath + '/index.html'
console.log(filePath)
fs.access(filePath, fs.F_OK | fs.R_OK, function(err) {
if (err) {
response.writeHead(404, { 'Content-Type' : 'text/html' })
response.end('<h1>File not found</h1>')
} else {
fs.readFile(filePath, function(err, contentFile){
if (!err) {
response.writeHead(200, { 'Content-Type' : 'text/html' })
response.end(contentFile)
} else {
response.writeHead(500, { 'Content-Type' : 'text/html' })
response.end('<h1>Can not read this content</h1>')
}
})
}
})
}).listen(3500)
但是当我访问http://localhost:3500/ 时,它会说:
【问题讨论】:
-
如果您将这一行
response.end(contentFile)更改为:response.write(contentFile); response.end();是否有效? -
还是一样的问题。
-
请在
console.log(filePath)行之前添加:console.log(baseURI.pathName)。结果如何? -
嗨@RicardoPontual,它打印
undefined -
这就是问题所在。尝试像这样设置文件路径进行测试:
var filePath=folderPath + '/index.html'