2017-10-28 68 views
-1

我正在使用fs模块在nodejs中读取此文件。 我收到了两次回复。让我知道我做错了什么。这是我的代码。如何在节点应用程序中使用fs读取文件?

var http = require("http"); 
var fs = require("fs"); 

http.createServer(function(req, res) { 
    fs.readFile('sample.txt', function(err, sampleData) { 
    console.log(String(sampleData)); 
    //res.end(); 
    }); 
    console.log("The end"); 
    // res.writeHead(200); 
    res.end(); 
}).listen(2000); 

在浏览器中点击端口后。我在终端上收到了两次回复。这是输出。

The end 
this is sample text for the testing. 

The end 
this is sample text for the testing. 
+1

的代码将不工作。结果并不适合它。 –

+0

sample.txt包含“这是测试的示例文本”。 –

回答

3

你最有可能得到它两次,因为你是从浏览器访问http://localhost:2000/

当这样做时,实际上有两个请求正在进行。您的实际请求和favicon :)两者都由您的服务器处理。

看一看Chrome的调试器 - >网络

enter image description here

+0

哦..现在我明白了。 –

0

您可能文件到客户端:

fs.createReadStream('sample.txt').pipe(res); 
+0

我想查看终端控制台中的响应。我得到了res两次。我只想知道为什么我得到它两次。 –

2

两个日志消息会出现:一个用于/,另一个用于/favicon.ico

您可以通过添加的console.log验证这一点(req.url);

为了避免这种情况:

var http = require("http"); 
    var fs = require("fs"); 

    http.createServer(function(req, res){ 
    if(req.url === '/'){ // or if(req.url != '/faicon.ico'){ 
     fs.readFile('sample.txt', function(err , sampleData){ 
      console.log(String(sampleData)); 
      res.end(); 
     }); 
    console.log("The end"); 
    } 

    // res.writeHead(200); 
}).listen(2000); 
+0

是的,这是工作。 –

+0

这种情况适用于我>> if(req.url!='/favicon.ico') –

1

的请求时,自动favicon.io。 为了避免自动请求图标,则可以执行以下操作

http.createServer(function(req, res){ 
    if(req.url != '/favicon.ico'){ 
     fs.readFile('sample.txt', function(err , sampleData){ 
      console.log(String(sampleData)); 
      res.end(); 
     }); 
     console.log("The end"); 
    } 

}).listen(2000); 

O/P =>

The end. 
this is sample text for the testing. 
相关问题