Article From:https://segmentfault.com/q/1010000012136486
Question:

1.Question:
console.log(html),Console output is successful, but res.end (HTML) cannot render pages.

2.Code

var http = require("http");
var path = require("path");
var url = require("url");
var fs = require("fs");
var ejs = require("ejs");

var server = http.createServer(function (req, res) {
    if (req.url == "/favicon.ico") {
        return;
    }
    var pathname = url.parse(req.url).pathname;
    var fileUrl = path.normalize("./public/" + pathname);
    var extname = path.extname(pathname);

    fs.readFile(fileUrl, function (err, fileData) {
        getMime(extname, function (mime) {
            res.writeHead(200, { "context-type": mime });
            res.end(fileData);
        })
    });



    if (pathname == "/") {
        var _thisUrl = "./public"
        var fileArry = [];//Storing some of the data of the individual file dataVar a = {}Var data = {}; / / store file (whether file, 1 is, 0 not); fileName: file (folder) name; url:Actual address of the fileFs.readdir (_thisUrl, function (err, files) {Var length = files.length;(function iterator (I) {)Var show = 0;If (I > = files.l)Ength) {Data = {{"Fa"): fileArry, "length": length};Fs.reAdFile ("./views/index.ejs", function (err, fileData) {Var template = fileDAta.toString ();Var HTML = ejs.render (template, data);Console.log (HTML);Res.end (HTML);});Return;}Fs.stat (_thisUrl + "/" + files[i], function (err, STA)TS) {If (stats.isDirectory ()) {A = {"file"): 0, "fileNAme ": files[i]," URL ": _thisUrl +" / "+ files[i]}"}Else {If (path.extname ("+" + files[i]).ToLocaleLowerCase () = = ".Jpg") {Show = 1;}A = {"file"): 1, "filEName ": files[i]," URL ": _thisUrl +" / "+ files[i]", "show": Show}}FileArry.push (a);//console.log (fileArry);Iterator(I + 1);})}) (0);});};});Server.listen (3000, "127.0.0.1 ");Function getMime (extname, FN) {Fs.readFile ("./public/mime.json", function (err, data)) {Var mimeList = JSON.parse (data);Var mime = mimeList[extname];FN (MIME);})}

3.Console screenshot

I am Xiao Bai, please explain slightly more, thank you.
PS:Later, consol.log (RES) found that the res of the self executing function is different from that of the external res, and the res inside the self executing function seems to be much less.

Answer 0:
if (extname) {
        return fs.readFile(fileUrl, function (err, fileData) {
            if (err) {
                res.writeHead(404, 'not found');
                return res.end();
            }
            getMime(extname, function (mime) {
                if (!mime) {
                    res.writeHead(404, 'not found');
                    return res.end();
                }
                res.writeHead(200, { "context-type": mime });
                res.end(fileData);
            })
        });
    }

It should be the previous piece that has returned before you export HTML, and should make full judgement before.
And that is why these read files do not read the cache directly when the application is started, do not do it in the linstener function, so that every request will be read after the request, and the performance is greatly reduced.

The logic that reads the file in the back of the loop is not right, because it is asynchronous, and at the time of render, it doesn’t guarantee that all the file information in the fileArry is already available.

Answer 1:

Because reading files is asynchronous, when you finish reading the file, the request has been processed.

Answer 2:
fs.readFile(fileUrl, function (err, fileData) {
        getMime(extname, function (mime) {
            res.writeHead(200, { "context-type": mime });
            res.end(fileData);  ```//Your end here ends the response directly, leading to the following data.})});

Answer 3:

It can be changed to the following way:
var rs = fs.createReadStream(__dirname + ‘/test.txt’)
rs.on(‘data’, function (data) {
console.log(data.toString());
});
rs.on(‘end’, function () {
console.log(‘Read the end of the file ‘)
});

Leave a Reply

Your email address will not be published. Required fields are marked *