为什么node.js多次显示相同的内容?

我有一个代码,显示HTML文档(其中包括.jpg图像)和一个代码,创build一个新的.txt文件,将数据保存并显示在控制台。

但每次我运行这个代码与谷歌铬,数据显示3倍…

var http = require('http'); var fs = require('fs'); var path = require('path'); http.createServer(function (request, response) { //branje HTML datoteke var file_path = '.' + request.url; if (file_path == './') file_path = './func.html'; var extname = path.extname(file_path); var contentType = 'text/html'; switch (extname) { case '.jpg': contentType = 'image/jpg'; break; } fs.readFile(file_path, function (error, content) { if (error) { if (error.code == 'ENOENT') { fs.readFile('./404.html', function (error, content) { response.writeHead(200, { 'Content-Type': contentType }); response.end(content, 'utf-8'); }); } else { response.writeHead(500); response.end('Server error!: ' + error.code + ' ..\n'); response.end(); } } else { response.writeHead(200, { 'Content-Type': contentType }); response.end(content, 'utf-8'); } }); fs.writeFile("external-data.txt", "- TEXTFILE-CONTENT\n", function (err) { if (err) { return console.log(err); } console.log("Data saved!\n"); }); fs.readFile(__dirname + '//external-data.txt', function (err, data) { console.log(data.toString()); response.end(data); }); 

结果

在这里输入图像说明

有什么build议么? 代码有什么问题,为什么它会多次显示相同的文本而不是一次? 谢谢!

在Chrome中打开开发者工具。 看看networking标签。 提出请求。

你会看到Chrome做出多个请求。 例如,对于/favicon.ico

每个请求都会触发您的代码。