The fs.readFileSync function does not recognize the HTML-file, even tho it is localted in the same folder. The error says: Error: ENOENT: no such file or directory, open 'node.html'
const http = require('http');
const PORT = 3000;
const fs = require('fs')
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, {'content-type': 'text/html'});
const homePageHTML = fs.readFileSync('node.html');
console.log(homePageHTML)
res.end()
} else {
res.writeHead(404, {'content-type': 'text/html'});
res.write('<h1>Sorry, you were misled!</h1>')
res.end()
}
})
server.listen(PORT);
CodePudding user response:
I solved It by changing the path to ${__dirname}\node.html. Somehow needs the actual path. Which doesn't seems to be the case in the tutorial I'm watching.
CodePudding user response:
Sometimes trying a basic npm reinstall can help:
npm install
I also noticed another problem when trying to reproduce your problem. You didn't specify and encoding type in your fs.ReadFileSync
method, so the console.log
outputted a buffer rather than a string. changing your homePageHTML
string line into this should work
const homePageHTML = fs.readFileSync('node.html', "utf8");
Let me know if this works or if you have any other problems.