Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
How to properly use response.end () in Node JS when reading a file asynchronously

I am to Node JS decided to create a simple routing where the file is read based on the url.

My problem is that I don't quite understand how to use response.end correctly.

This is my code without using response.end

http
  .createServer(function (req, res) {
    if (req.url === "/students") {
      fs.readFile("./templates/students.html", function (err, data) {
        if (!err) {
          res.write(data);
        }
      });
    } else {
      res.write('Page not found.')
    }
  })
  .listen(3000);

When I apply response.end inside a file read, then the else condition with an empty url stops working (as expected)

enter image description here

Otherwise, only the else condition works, and reading the file does not work when added at the end of url /students

enter image description here

This has always been a problem for me, I don’t understand how to use response.end correctly. It’s always confused me. How can I solve this problem?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!