Node.js

It’s an asynchronous event driven JavaScript Runtime. it’s designed to build scalable network applications.

  • it’s actually not a framework, instead it’s a runtime environment. it enables us to use javescript on a computer and not just limited to wihtin the browser.

Express, on the other hand is actually a javascript framework that allow us to create backend for our websties.

fs module

introduction

In JavaScript, the term “fs” typically refers to the “File System” module. The “fs” module is a built-in module in Node.js, which is a JavaScript runtime environment used for server-side applications.

The “fs” module provides methods and functionality to interact with the file system, allowing you to read from and write to files, create directories, modify file permissions, and perform other file-related operations. It enables you to work with files and directories on your computer or server.

Here’s an example of how you can use the “fs” module in Node.js to read the contents of a file:

1
2
3
4
5
6
7
8
9
javascriptCopy codeconst fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});

In the above example, fs.readFile is used to read the contents of the file named “file.txt” in the current directory. The callback function receives any potential error (err) and the file contents (data). If no error occurs, the contents of the file are printed to the console.

Note that the “fs” module is specific to Node.js and is not available in web browsers, as JavaScript running in a browser has limited access to the local file system for security reasons.

Synchronous vs. Asynchronous

Node.JS only has one thread and all the users accessing your application are using this thread.

  • Synchronous code is also called blocking code because a certain operation can only be executed after the one before has finished.

    eg. readFileSync

  • Asynchronous code is non-blocking code. Asynchronous code is a programming paradigm that allows multiple tasks to be executed concurrently without blocking the execution of the program. While one task is being processed asynchronously, the program can execute other tasks or respond to user input, improving responsiveness and overall performance.

eg.readFile

in synchronous, if one user locks the single thread, all the other users need to wait.

in asynchronous, it does the heavy work in the background, and once the data is available, the call back function will get called in the single thread to access the single data. At the same time all the users can perform their tasks one after another in the single thread.

callback hell

Callback hell is a situation that arises in asynchronous programming when multiple nested callbacks are used, leading to complex and unreadable code. It occurs when one asynchronous operation depends on the result of another, resulting in deeply nested callback functions.

NPM

install npm command: npm init (type in the terminal opened in the project)

after installing successfully, there will be a file called package.json

1
2
3
4
npm init

npm install nodemon --save-dev
// it will automatically restart the server when there's a change

when we ran this command, we install the package locally so it mean it can only work in this project.

But if you install a package globally then you don’t need to install that package each time you have a new project.

1
2
3
// install globally:
npm i nodemon --global

use nodemon ( globally):

1
nodemon index.js

require 3rd party module

1
2
3
4
5
const slugify = require('slugify');


console.log(slugify('Fresh Avocado', {lower:true})); //fresh-avocado

package version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"devDependencies": {
"nodemon": "^2.0.22"
}
// ^ means we accept patch and minor fixes
and ~ means we only accept path releases (safest)
* means we accept all releases (not recommend)
this will affect the outcome when we run npm outdated command
// 2 is major version (the chagne of this number might affect the code we already have )
// 0 is minor version (introduce some new features into the packes, but not including breaking changes, the increase of this number will not break our code )
//22 is the patch version ( is for bug fixs)


//update package
npm outdated //will give us a list of packages that are outdated
npm update slugify // will update the version of slugify according to whther it's ^ or ~


//delete package
npm uninstall express

node_modules folder:

it has all the dependencies.

there’s no need to share this folder when you share your code with other people because it’s very big.

when we download someone’s node without this folder, how do we install those dependencies ourselfves

1
2
npm install
// it will read packages.json file read those dependencies and downlaod them all

package-lock.json file: it has all the versions and names and details of the packages that we are using.

when you share your code or you use other people’s code, you want all the versions of those packages to be the same so the code works the same for the everyone. So make sure you always share both package.json file and package-lock.json

note

  • enter node repo:

XIANGDANTONG@EGG ~ ❯❯❯ node
Welcome to Node.js v16.15.0.
Type “.help” for more information.

fs

file system

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//require module
const fs = require("fs");

//write a file and save it
fs.writeFile("messgae.txt", "hello from nodejs", (err) => {
if (err) throw err;
console.log("the file has been saved!");
});

//read a file
fs.readFile("message.txt", "utf-8", (err, data) => {
if (err) throw err;
console.log(data);
});

npm (node pacakge manager

1
2
 // it brings up the initialization utility, create configuration file which is called the package.json
❯ npm init
  • install npm package:

npm i packagename1 name2 name3 // i is short for install

  • string interpolation:
1
2
3
4
5
var generateName = require("sillyname");
var sillyName = generateName();

console.log("my name is " + sillyName);
--->console.log(`my name is ${sillyName}`);
  • CJS ->common JS

    ESM ->ecmascript module

another way to require module

CJS or ESM you can only choose one in the project

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package.json:
{
...
"main": "index.js",
-->"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
... ini
}

js:
//var generateName = require("sillyname");

-->import generateName from "sillyname";
var sillyName = generateName();
console.log(`my name is ${sillyName}`);

Express

a javascript framework.

  • add module:
1
npm install express
  • creating a server:

    1
    2
    3
    4
    5
    6
    7
    8
    //require express module
    const express = require("express");
    const app = express();
    // listeing on port 3000
    app.listen(3000, function () {
    console.log("listening on port 3000");
    });

  • routes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//require express module
const express = require("express");
const app = express();

//what should happen when someone make a get request to the home route
// "/" means home root
// when that request gets made at that home location, then this callback gets triggered and we send the browser a response
app.get("/", function (req, res) {
res.send("<h1>hello12</h1>");
});

app.get("/contact", function (req, res) {
res.send("<h1>contact</h1>");
});

app.get("/about", function (req, res) {
res.send("call me maybe");
});
// listeing on port 3000
app.listen(3000, function () {
console.log("listening on port 3000");
});

TEMPLATE

  • Make a new folder

  • Inside the folder, create a new file called sth.js

  • Set up a new NPM package npm init -y

  • Using NPM install the express module

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    npm install express

    //require express module
    const express = require("express");
    const app = express();

    app.get("/about", function (req, res) {
    res.send("call me maybe");
    });
    // listeing on port 3000
    app.listen(3000, function () {
    console.log("listening on port 3000");
    });
  • Require express in your calculator.js

  • Setup express

  • Create a root route get method with app.get()

Body Parser:

allow us to pass the information that we get sent from post request.

  • install:

npm i body-parser

caculator project:

js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const express = require("express");
const app = express();
const bodyParser = require("body-parser");

// trying to grab the information that gets posted to your server from an HTML form
// extended: true -> allow us to post nested objects
app.use(express.urlencoded({ extended: true })); // it allows us to go to any of our routs and req.body

app.get("/", function (req, res) {
// res.sendFile("index.html");
res.sendFile(__dirname + "/index.html"); // __dirname is a constant that allows us to grab hold of the current file location at any give time
});

app.post("/", function (req, res) {
var n1 = Number(req.body.num1);
var n2 = Number(req.body.num2);
var ans = n1 + n2;
// res.send("result" + res);
// console.log(req.body); //parsed version of http request
res.send("result is " + ans);
});
// listeing on port 3000
app.listen(3000, function () {
console.log("listening on port 3000");
});

html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>calculator</h1>
<form action="/" method="post">
<input type="text" name="num1" placeholder="First Number">
<input type="text" name="num2" placeholder="Second Number">
<button type="submit" name="submit">Calculate</button>
</form>

</form>
</body>
</html>

BMI Caculator

1
2
3
4
5
6
7
8
9
app.get("/bmicalculator", function (req, res) {
res.sendFile(__dirname + "/bmiCalculator.html");
});
app.post("/bmicalculator", function (req, res) {
var w = parseFloat(req.body.weight);
var h = parseFloat(req.body.height);
res.send(w + " " + h);
res.send(req.body);
});