Node.js from fs.readFileSync() to fs.readFile()

寵の児 提交于 2019-11-30 11:46:56

问题


I'm trying to get my head around synchronous vs asynchronous in Node.js, in particular for reading an html file.

In a request handler, the synchronous version that i'm using, which works is the following:

var fs = require("fs");
var filename = "./index.html";
var buf = fs.readFileSync(filename, "utf8");

function start(resp) {
    resp.writeHead(200, {"Content-type":"text/html"});
    resp.write(buf);
    resp.end();
    }

exports.start=start; 
  1. What would be the version using readFile() ??
  2. I understand that readFile is asynchronous so theoretically I should wait that the entire file is read before rendering it, so should I introduce an addListener? I might be confusing different things.

Edit: I have tried to refactor the code like this:

var fs = require("fs");
var filename = "./index.html";
function start (resp) {
    resp.writeHead(200, {"Content-Type":"text/html"});
    fs.readFile(filename, "utf8", function (err, data) {
        if (err) throw err;
        resp.write(data);
        });
    resp.end();
    }

I get a blank page, I guess it's because it should wait that all the data has been read, before resp.write(data), how do i signal this?


回答1:


var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}



回答2:


This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}


来源:https://stackoverflow.com/questions/22863170/node-js-from-fs-readfilesync-to-fs-readfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!