Node is a runtime that allows you to run JavaScript on the server. Learn more in the Fireship.io - now JavaScript works section of this course.
Mac/Linux NVM for Mac & Linux.
Windows NVM for Windows.
Use Node Version Manager (NVM) to manage your installation. Install the latest Long-Term Support (LTS) version, nvm install --lts
.
Find out if Node is installed on your system by running node -v
on the command line.
For trying out basic Node, you can use its REPL (Read Eval Print Loop)
>_command line
node
>_command line Node REPL
console.log('hello world')
>_ hello world
prints in the terminal.
Use ctrl+c to shut it down.
For anything more that testing basics, create a JavaScript file.
In code editor, create a file called index.js (default entry point for NodeJS files) and code the following:
// index.js
console.log("Hello World");
Run it with node
.
node index.js
# OR
node . # points to index.js
Node has sever global variables that you should know about:
global
namespace available througout Node process. Use it to save global variables throughout the app. Similar towindow
in the browser.process
interact with the current Node process to access information like the OS platform or environment variables.
Node.js System Diagram
In most cases you will find yourself listening to events and handling them with callbacks, but you can create your won events with an EventEmitter
.
// Step 5 - Events && Emitters
// create
const { EventEmitter } = require("events");
const eventEmitter = new EventEmitter();
// handle
eventEmitter.on("lunch", () => {
console.log("yum 🌭");
});
// emit
eventEmitter.emit("lunch");
eventEmitter.emit("lunch");
// yum 🌭
// yum 🌭
Many APIs in Node are callback based.
Setup external text file called 'hello.txt' in the same directory as index.js
Just Hello!!!
// Step 6 - Work with the File System
const { readFileSync } = require("fs");
// Blocking - (utf-8 is the encoding type)
const txtBlock = readFileSync("./hello.txt", "utf-8");
console.log("1", txtBlock);
// Non-blocking
let { readFile } = require("fs").promises;
// readFile("./hello.txt", "utf8", (err, txt) => {
// if (err === null) {
// console.log("2", txt);
// } else {
// console.log("err", err);
// }
// });
// with promises - also, non-blocking
async function HelloWorld() {
try {
var promiseTxt = await readFile("./hello.txt", "utf-8");
console.log(promiseTxt);
} catch (e) {
console.log("err", e);
}
}
HelloWorld();
console.log("Do this ASAP");
// const promiseTxtAsync = await readFile('./hello.txt', 'utf-8'); // Node 14+
In version 14.3+ of Node this 'top-level await' will work
but in lower Node versions, 'await' must be inside 'async func'
var file = await readFile('hello.txt', 'utf-8');
console.log(file);
wrap in parens them follow with parens to create IIFE
(immediately invoked function expression... self executes!)
Setup an external module in the same directory as index.js
Create a module which is a file that exports its code so it can be imported and used elsewhere
// file: my-module.js
module.exports = {
hello: 'Just Hello';
}
// Step 7 - Modules and NPM
const { hello } = require("./my-module.js");
console.log(hello);
console.log(hello);
console.log(hello);
Create a HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Express App</title>
</head>
<body>
<h1>This is my first node web app!</h1>
</body>
</html>
- Use express to build a HTTP endpoint
- Read the HTML file
- Send it back to the client
// Step 7 - Modules and NPM
const { hello } = require("./my-module.js");
console.log(hello);
console.log(hello);
console.log(hello);
const express = require("express");
const app = express();
const { readFile } = require("fs").promises;
app.get("/", async (req, res) => {
res.send(
await readFile("./app.html", "utf-8", (err, html) => {
if (err) {
res.status(500).send("sorry, out of order");
}
res.send(html);
}),
);
});
app.listen(process.env.PORT || 3000, () =>
console.log(`App available on http://localhost:3000`),
);
Create a Google Cloud account and install the gcloud SDK.
Configure your server.
runtime: nodejs12
Deploy it!!!
gcloud app deploy