jeudi 2 juillet 2020

Changing html page file within node.js using fs module

I was trying to learn node.js and back-end stuff and got this problem. Can anyone help? This is my code. I am trying to change html page from h1.html to h2.html where I get (Error [ERR_STREAM_WRITE_AFTER_END]: write after end)

var serverFunction = function (req, res) {

var q = url.parse(req.url, true);
var status = "";
var name = "";

if (q.pathname == "/login") {
    name = q.query["name"] + ":";
    fs.readFile('./h2.html', function(err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.write(status);
        return res.end();
    });
}

if(q.pathname == "/send" && "msg" in q.query)
{
    var msg = q.query["msg"];
    SaveMsg(msg, name);
}

if (q.pathname == "/show") {
    res.writeHead(200, {'Content-Type': 'text/html'});
    GetMessages((result) => {res.end(result);} );
}

else {
    fs.readFile('./h1.html', function(err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.write(status);
        return res.end();
    });
}

};

Full error text:

events.js:287
      throw er; // Unhandled 'error' event
      ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at write_ (_http_outgoing.js:637:17)
    at ServerResponse.write (_http_outgoing.js:629:15)
    at C:\Users\parsa\Desktop\T\s.js:55:17
    at FSReqCallback.readFileAfterClose [as oncomplete] 
(internal/fs/read_file_context.js:63:3)
Emitted 'error' event on ServerResponse instance at:
    at writeAfterEndNT (_http_outgoing.js:692:7)
    at processTicksAndRejections (internal/process/task_queues.js:85:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}



Aucun commentaire:

Enregistrer un commentaire