Reputation: 152
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);
Upvotes: 0
Views: 5059
Reputation: 708026
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");
Upvotes: 2
Reputation: 152
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.
Upvotes: 1
Reputation: 67
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.
Upvotes: 0