我正试图从我的节点应用程序中显示一个html文件。这是我的代码:
var http = require('http');
var fs = require ('fs');
var path = require("path");
var filePath = path.normalize('/NodeJS/projects/test.html');
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type' : 'text/html'});
var myReadStream = fs.createReadStream(filePath);
myReadStream.pipe(res);
});
server.listen(3000, '127.0.0.1');
console.log('listening to port 3000');
我之前在尝试使用__dirname时遇到了同样的问题,但它不起作用,所以我想尝试使用path.normalize。任何关于为什么这不起作用的线索。如果我将控制台错误中的目录复制到我的资源管理器中,我的test.html文件将打开。。。。文件就在那里。这一定是一个简单的错误,但它杀死了我
我认为这可以用一种更简单的方法来完成。
我的文件在根文件夹中
path.normalize()
方法对给定路径进行归一化,解析..
和.
段。
path.normalize('/foo/bar//baz/asdf/quux/..');
// Returns: '/foo/bar/baz/asdf
var http = require('http'),
fs = require('fs');
var path = require("path");
var filePath = path.normalize('./index.html');
console.log(filePath)
//here you can include your HTML file
fs.readFile(filePath, function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(3000);
});