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);
The logical explanation for your issue is that when you start your program the current working directory in the OS is not the directory that contains your node.html
file. Thus, fs.readFileSync('node.html', "utf8");
which only looks in the current working directory does not find the target file.
As you discovered, you can fix the problem by building a more complete path that specifies that actual directory you want, not just the plain filename. You could also make sure that the current working directory was set properly to your server directory before you started your app.
The usual way to build your own path to your server directory is by using path.join()
:
fs.readFileSync(path.join(__dirname, 'node.html'), "utf8");