簡體   English   中英

如何在節點應用程序中使用fs讀取文件?

[英]how to read file using fs in node app?

我正在嘗試使用fs模塊在nodejs中讀取此文件。 我得到了兩次回應。 讓我知道我在做什么錯。 這是我的代碼。

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.

您很可能兩次獲得它,因為您正在從瀏覽器訪問http:// localhost:2000 /

這樣做時實際上有兩個請求。 您的實際請求和favicon :)都由服務器處理。

看看Chrome調試器->網絡

在此處輸入圖片說明

將出現兩則日志消息:一條為/,一條為/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);

自動向favicon.io發出請求。 為了避免自動請求favicon,您可以執行以下操作

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.

您可以將文件通過管道傳輸到客戶端:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM