0
import http from "http"
import fs from "fs"

function readDemo(path){
    return new Promise((resolve,reject)=>{
        fs.readFile(path,(err,data)=>{
            if(err)
                reject(err);
            else
                resolve(data);
        })
    })
}

const server = http.createServer((req,res)=>{
    if(req.url === `/`){
        res.writeHead(200,{"Content-type":"text/html"});
        readDemo(`./todo.html`)//
            .then(data => res.write(data))
            .catch(console.log);
        res.end();
    }
})

server.listen(5000);

I'm trying to load todo.html by requesting localhost:5000 as running my own server in Nodejs
It seems fs.readFile took long time to load css and javascript section so I made Promise statement to make res.write waiting for fs.readFile to finish load todo.html include css and javascript linked in it.

However code set err says

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

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at writeAfterEnd (_http_outgoing.js:668:15)
    at write_ (_http_outgoing.js:680:5)
    at ServerResponse.write (_http_outgoing.js:661:15)
    at file:///C:/Users/KUSW-14/Downloads/web_study-main/web_study-main/to_do_list/main.js:19:31   
Emitted 'error' event on ServerResponse instance at:
    at writeAfterEndNT (_http_outgoing.js:727:7)
    at processTicksAndRejections (internal/process/task_queues.js:81:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}  

Can anyone help me what's wrong with my code?

1

1 Answer 1

1

The readFile() is non-blocking so you're calling res.end() BEFORE you call res.write(). I'd suggest using await like this:

const server = http.createServer(async (req, res) => {
    if(req.url === `/`){
        try {
            const data = await readDemo(`./todo.html`);
            res.writeHead(200,{"Content-type":"text/html"});
            res.write(data)
            res.end();
        } catch(e) {
            console.log(e);
            res.writeHead(500);
            res.end();
        }
    } else {
        res.writeHead(404);
        res.end();
    }
});

Without await, you need to move the res.end() inside of the .then():

const server = http.createServer((req,res)=>{
    if(req.url === `/`){
        readDemo(`./todo.html`).then(data => {
            res.writeHead(200,{"Content-type":"text/html"});
            res.write(data);
            res.end();
        }).catch(err => {
            console.log(err);
            res.writeHead(500);
            res.end();
        });
    } else {
        res.writeHead(404);
        res.end();
    }
});

FYI, in modern versions of node.js fs.promises.readFile() is already a promise version so you don't have to make your own.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.