为什么 fs.readFile (Node.js) 的文件名参数前有一个点?



在 Node.js 的 URL 模块 (https://www.w3schools.com/nodejs/nodejs_url.asp( 的教程之后,我注意到文件名在成为 fs.readFile 的参数之前有一个起始点(第 7 行(。服务器返回不带点的 404,但我无法理解原因。你能帮忙吗?

var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname; // here it gets the DOT
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}  
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);

正如文章所述,q.pathname/default.htm

var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'

/default.htm是绝对文件路径,fs.readFile从根目录中读取,而./default.htm是相对路径,fs.readFile从当前工作目录中读取它。

应该提到的是,字符串连接不是创建文件路径的安全方法,最好使用path.join来完成:

var path = require('path');
...
var filename = path.join(".", q.pathname); // === 'default.htm'

前导点的原因是该示例的逻辑是打开本地文件。
q.pathname将返回类似/...,因此在它前面添加一个.,你会得到类似./...,它标识运行 node.js 程序的同一目录中的文件。

最新更新