How to Build a Web App with JavaScript

Finally, it is time for us to create our first real web application using JavaScript. First of all, there are two packages we must discuss.

The file system module

Let's start with the file system (fs) module. This package is built into Node.js, so you don't need to install anything. Instead, create a new server.js file for the code and a data.txt file for JavaScript to read and write.

text
1.
2├── data.txt
3├── package-lock.json
4├── package.json
5└── server.js
javascript
1import { readFile } from "fs";
2
3// Specify the file we want to read as well as the charset encoding format
4readFile("data.txt", "utf8", (error, text) => {
5  if (error) throw error;
6
7  console.log(text);
8});

We can also write to the file like this:

javascript
1import { writeFile } from "fs";
2
3writeFile("data.txt", "Hello, World? Hello, World!", (error) => {
4  if (error) {
5    console.log(`${error}`);
6  } else {
7    console.log("File written.");
8  }
9});

In this case, it is not necessary to specify the encoding format. If writeFile is given a string, it will simply assume the default format, which is UTF-8.

We are revisiting the fs module because for this project, we are going to use a text file as a database, as we will demonstrate later.

The HTTP module

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉