Giter Site home page Giter Site logo

nodejs-basics's Introduction

Node.js

Node.js Ultimate Beginner's Guide in 7 Easy ๐Ÿง

Fireship.io

Fireship.io - learn Node

Step 1 - What is Node?

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.

Step 2a - Install Node Version Manager (NVM)

Mac/Linux NVM for Mac & Linux.

Windows NVM for Windows.

Step 2b - Install Node

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.

Step 3 - Hello World

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

Step 4 - Builtins & Globals

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 to window in the browser.
  • process interact with the current Node process to access information like the OS platform or environment variables.

Step 5 - Events and Emitters

Node.js System Diagram

Node-system-diagram

node-async-event-driven

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 🌭

Step 6 - Work with the File System

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!)

Step 7 - Modules and NPM

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);

Use Express to create a HTTP endpoint

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>
  1. Use express to build a HTTP endpoint
  2. Read the HTML file
  3. 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`),
);

Deploy App to Google Cloud Engine

Create a Google Cloud account and install the gcloud SDK.

Configure your server.

runtime: nodejs12

Deploy it!!!

gcloud app deploy

nodejs-basics's People

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.