I am currently working with Node.js servers. When I access the server, the following code executes:
res.write("Whatever text you choose");
For example, when I navigate to localhost:9090
, I receive the expected file. However, if I try to access localhost:9090/index.html
, localhost:9090/funnyFile/Jokes.html
, or localhost:9090/myProjects/poj1/index.html
, I still receive the same file. I would like to know how to configure the server to serve different files based on the URL path.
Here is the code for my Node.js server:
const http = require('express')
const port = 9090
// Create a server object:
const server = http.createServer(function (req, res) {
// Write a response to the client
res.write("I choose this text");
// End the response
res.end()
})
// Set up our server so it will listen on the port
server.listen(port, function (error) {
// Checking any error occur while listening on port
if (error) {
console.log('Something went wrong', error);
}
// Else sent message of listening
else {
console.log('Server is listening on port' + port);
}
})
Turns out I needed to install and require both fs and path (and use http instead of express). This works very well (unless you are importing something):
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, req.url);
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
fs.readdir(__dirname, (err, files) => {
if (err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'text/plain');
res.end('Internal Server Error');
return;
}
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end(`This page can't be found. Available files:\n${files.join('\n')}`);
});
return;
}
fs.createReadStream(filePath).pipe(res);
});
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Although I like the answer provided by M Z.