You decide to put all the ideas you just read about together as you write your own custom file server. You will run it on your local computer. The special host name localhost
always refers to the local computer. The server will listen on port 5000. Following the examples you find in the Node.js documentation, you write this code using the http
library, passing arrow functions wherever callbacks are expected:
const http = require('http');
const hostname = 'localhost';
const port = 5000;
const server = http.createServer((request, response) => {
console.log(`The client requested ${request.url}...`);
});
server.listen(port, hostname, () => {
console.log(`We're live on port ${port}!`);
});
Try running this script and visiting http://localhost:5000/
in your browser. You should see the log message appear in your terminal. Try adding path components at the end of the URL, like http://localhost:5000/index.html
.
The request
parameter is the incoming HTTP request. The response
parameter is the outgoing HTTP response. The job of the callback is to configure the response.
You want to treat the path component at the end of the URL as the name of a file in the script's directory, read in the file, and send it back to the client. You add in code to read the file using a promise:
const server = http.createServer((request, response) => {
console.log(`The client requested ${request.url}...`);
const fileName = request.url.substring(1); // strip off the leading /
fsPromises.readFile(fileName, 'utf8')
.then(text => {
// send text to client
})
.catch(error => {
// file couldn't be read
});
});
When the file can't be found, you decide to return a 404 error code:
const server = http.createServer((request, response) => {
console.log(`The client requested ${request.url}...`);
const fileName = request.url.substring(1); // strip off the leading /
fsPromises.readFile(fileName, 'utf8')
.then(text => {
// send text to client
})
.catch(error => {
response.statusCode = 404;
response.end();
});
});
When the file can be found, you return a success code of 200 and write the file contents to the body of the response:
const server = http.createServer((request, response) => {
console.log(`The client requested ${request.url}...`);
const fileName = request.url.substring(1); // strip off the leading /
fsPromises.readFile(fileName, 'utf8')
.then(text => {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/plain');
response.write(text);
response.end();
})
.catch(error => {
response.statusCode = 404;
response.end();
});
});
Try running the script with the name of a file in your current directory at the end of the URL. Do you see the contents appear in the browser window? Try an invalid file name. Does your browser report the 404 error?
This file server is not secure in that it injects strings from the requested URL into your local file system. Don't build a product around it.