Bootcamp
Search…
📅
Course Schedule
0: Language and Tooling Teaching Guide
1: Frontend Basics Teaching Guide
2: Backend Basics Teaching Guide
3: Backend Applications Teaching Guide
4: Backend Structure Teaching Guide
5: Full-Stack Applications Teaching Guide
6: Frontend Infrastructure Teaching Guide
7: React Teaching Guide
8: Advanced React Teaching Guide
9: Advanced Topics Teaching Guide
🧮
Algorithms Teaching Guide
💼
Interview Prep Teaching Guide
☺
User Experience Teaching Guide
2.10: HTTP File Server

Introduction

Servers can respond to requests with arbitrary data, including files. Servers designed to return files to clients are known as "file servers". The request might specify a file path, and the server might respond with that file if it exists.
The Node.js file server can serve local files to computers that request them from the Internet.

History of the Web

The year is 1990. The internet is still a relatively small collection of interconnected mainframe computers, mostly owned by either academic institutions or by military organizations. The total number of computers on the internet was around 300,000. Tim Berners-Lee was working at CERN, the particle accelerator experiment in Switzerland. He wanted to develop a system for sharing information between the vast number of scientists and departments inside CERN. His solution was to take HTML, a language to describe text documents and write a program that could request and display those documents through the internet network. His application contained two new concepts. First was that, before the web, if people wanted to share documents they would have to explicitly download them through the internet network and use another application on their computer to view them, depending on what kind of document it was. Berners-Lee's software combined the attributes of a document downloader and viewer into a single thing called a web browser. It also dictated the document itself and the file format of the document. The second was that using hyperlinks, every document could explicitly reference another document or section of a document somewhere else on the network. This relatively simple mechanism, using the underlying TCP and DNS network functionality that had been around for a decade or more, produced a powerful set of interconnected digital documents. These ideas, conceived of 30+ years ago, cemented one of the foundational mechanisms of the internet that still underlies anything that happens in a browser.
The World Wide Web and web browsers were the main driving force behind the skyrocketing number of computers on the internet (as defined by taken IP addresses) from 300,000 in 1990 to 100,000,000 in 2000.

Example Web File Server

Our first complete HTTP application, an HTML file server, is JavaScript code that listens for network requests. The hard drive path of the file is put into the URL. When the code responds with the contents of a file that exists on the hard drive it is "serving" that file in the response. This architecture mimics the first one setup by Tim Berners-Lee in 1990 (but of course he also had to write the entire browser application as well).

index.js

1
import { createServer } from 'http';
2
import { readFile } from 'fs';
3
​
4
const handleIncomingRequest = (request, response) => {
5
// request.url contains the portion of the URL after the domain.
6
// E.g. for https://ra.co/index.html, request.url would return "/index.html".
7
console.log('request url', request.url);
8
​
9
// "." refers to the Unix filesystem ".", which represents the current directory.
10
const filePath = '.' + request.url;
11
​
12
readFile(filePath, (err, content) => {
13
if (err) {
14
console.error('error reading file', err);
15
return;
16
}
17
// Set the response code to 200 (i.e. OK)
18
response.writeHead(200);
19
// Send the response with the file content in utf-8 format
20
response.end(content, 'utf-8');
21
});
22
};
23
​
24
// Initialise server with request listener function handleIncomingRequest
25
// https://nodejs.org/api/http.html#http_http_createserver_options_requestlistener
26
// Use port 3004 by convention.
27
createServer(handleIncomingRequest).listen(3004);
Copied!

Create Text File to Serve

Create text file hello.txt with the following content. We will have our file server serve this file.

hello.txt

1
Hello My Text File.
Copied!

Run Server

When we execute index.js above, the code runs indefinitely at the server's .listen method. It waits for incoming requests until we press Ctrl+C (which sends an interrupt signal) to exit. Look for the running server process in the Activity Monitor (Mac) or Task Manager (Windows).
1
node index.js
Copied!

Make Request to Server from Browser

Visit http://localhost:3004/hello.txt from our browser to retrieve our hello.txt file content. localhost is the default domain name of servers running on our local machine, and has a corresponding IP address of 127.0.0.1. We use the path component of the URL to tell the readFile function where to look on the computer.
It's common practice to use URL paths to retrieve specific resources from servers. We can set up our servers to only expose certain files to clients, e.g. by setting up a public folder with only files that should be shared publicly, such as CSS files and other static resources like images. We will learn more about how to do this in later modules.

Exercise

  1. 1.
  2. 2.
    Execute the above code.
  3. 3.
    Request for a file that does not exist.
  4. 4.
    Create an HTML file in the same directory and request for it from the browser.
  5. 5.
    Observe the request to the server in the Chrome DevTools Network tab.
  6. 6.
    Copy all files from the Video Poker project into the directory and request for the HTML file from the browser. Does the game work?
    1. 1.
      You may notice that your CSS files don't load. This is because when servers respond with non-text files, they need to send back a "Content-Type" header to let the client know what type of file it is, i.e. "MIME type".
    2. 2.
      Past student Zaffere wrote an explanation of how browsers determine content types here.
    3. 3.
      ​Here is an example server that sets the Content-Type header.

Further Reading

Last modified 2mo ago