new to node.js and was following a basic tutorial at link below. https://www.tutorialspoint.com/nodejs/nodejs_web_module.htm
var http = require('http');
var fs = require('fs');
var url = require('url');
// Create a server
http.createServer( function (request, response) {
// Parse the request containing file name
var pathname = url.parse(request.url).pathname;
// Print the name of the file for which request is made.
console.log("Request for " + pathname + " received.");
// Read the requested file content from file system
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP Status: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else {
//Page found
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// Write the content of the file to response body
response.write(data.toString());
}
// Send the response body
response.end();
});
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
created 2 files the index.html and the server.js completely identical to the post. Then when i try to run it with
node server.js
No error message shows up, but when i try to access the page on my browser it does not connect and an error shows up in the console.
Any help would be highly appreciated.
Server running at http://127.0.0.1:8081/
Request for / received.
{ Error: ENOENT: no such file or directory, open '' errno: -2, code: 'ENOENT', syscall: 'open', path: '' }
In the given code you have:
// Print the name of the file for which request is made.
console.log("Request for " + pathname + " received.");
// Read the requested file content from file system
fs.readFile(pathname.substr(1), function (err, data) {
Because the path is /
the pathname.substr(1)
will result in an empty string. And because you don't have a file that has no name, the fs.readFile
does not find a file to read which results in an ENOENT
error.
The given code does not automatically interpret an empty string as index.html
.
So you either have to use http://127.0.0.1:8081/index.html
in the browser. Or change the logic of the code to interpret the empty string as index.html
.