Node.js

Why learn Node.js?

Well all the cool kids are doing it! I mean, how cool does the MERN or MEAN stack sound? MongoDB, Express, React, Node. So much cooler than that silly old LAMP (Linux Apache, MySQL, PHP) stuff, right guys? Right?? Guys???

Notes:

NPM: Node Package Manager. Installs 3rd part packages (frameworks, libraries, tools, etc). Packages are stored in the the node_models folder. All dependencies are listed in the package.json file. `npm init` generates a new package.json file. `npm install express` installs the express package locally. `npm install -g nodemon` install nodemon globally. nodemon lets you make changes without restarted the server. ‘npm install -D nodemon’ installs it as a dev dependency.

Don’t deploy the node_models folder to a host, it can get very large. Instead delete and run npm install when you have it on the host.

When you export something from a file using `module.export = something` it is wrapped in a Module Function wrapper automatically:

(function(exports, require, modle, __filename, __dirname) {

})

import vs require:

Import is still expermental, but coming. Common JS, using require, is still more common.

Node.js Core Modules

The path module is very commonly used, gives use just the base file name.

const path = require("path");

// Base file name
console.log(__filename);
/// returns /home/lost/showcase/nodepractice/reference/path_demo.js
console.log(path.basename(__filename));
// Returns path_demo.js

// Directory name
console.log(path.dirname(__filename));
/// Returns /home/lost/showcase/nodepractice/reference

// File extension
console.log(path.extname(__filename));
// Returns .js

// Create path object
console.log(path.parse(__filename));
// Returns an object:
// {
//   root: '/',
//   dir: '/home/lost/showcase/nodepractice/reference',
//   base: 'path_demo.js',
//   ext: '.js',
//   name: 'path_demo'
// }

// Access parse object
console.log(path.parse(__filename).base);
// Returns path_demo.js

// Concatenate paths

console.log(path.join(__dirname, "test", "hello.html"));
// Returns /home/lost/showcase/nodepractice/reference/test/hello.html

fs Module

file system, can create folders and files, rename, read, append, overwrite

const fs = require("fs");
const path = require("path");

// Create folder
fs.mkdir(path.join(__dirname, "/test"), {}, (err) => {
  if (err) throw err;
  console.log("Folder created...");
});
//fs.mkdir takes in the file name, options, and a callback function.

//Create and write to file
fs.writeFile(
  path.join(__dirname, "/test", "hello.txt"),
  "Helloooo2222",
  (err) => {
    if (err) throw err;
    console.log("File written to...");
  }
);

// Create and append to file
fs.appendFile(
  path.join(__dirname, "/test", "hello2.txt"),
  "Helloooo",
  (err) => {
    if (err) throw err;
    console.log("File written to...");
    fs.writeFile(
      path.join(__dirname, "/test", "hello2.txt"),
      "again",
      (err) => {
        if (err) throw err;
        console.log("File written to...");
      }
    );
  }
);

//Read file
fs.readFile(path.join(__dirname, "/test", "hello.txt"), "utf8", (err, data) => {
  if (err) throw err;
  console.log(data);
});

//Rename file
fs.rename(
  path.join(__dirname, "/test", "hello.txt"),
  path.join(__dirname, "/test", "hello7.txt"),
  (err) => {
    if (err) throw err;
    console.log("##", "File renamed");
  }
);

os module

const os = require("os");

// Platform
console.log(os.platform());

console.log(os.arch());

console.log(os.cpus());

console.log(os.freemem());

console.group(os.totalmem());

console.log(os.homedir());

console.log(os.uptime());

Can get things like the OS, CPU arch, CPU Core Info

URL module

Crazy stuff

const url = require("url");

const myUrl = new URL("http://mywebsite.com/hello.html?id=100&status=active");

// Serialized URL
console.log(myUrl.href);
//Returns http://mywebsite.com/hello.html?id=100&status=active

//Host (root domain)
console.log(myUrl.host);
// Returns mywebsite.com

// Hostname
console.log(myUrl.hostname);
//Returns mywebsite.com, does not get port
//Different because it does not include a port if one was used

//Pathname
console.log(myUrl.pathname);
// Returns /hello.html

console.log(myUrl.search);
// Returns ?id=100&status=active

// Parems object
console.log(myUrl.searchParams);
// Returns URLSearchParams { 'id' => '100', 'status' => 'active' }

// Add param
myUrl.searchParams.append("abc", 123);
console.log(myUrl.searchParams);
// Returns URLSearchParams { 'id' => '100', 'status' => 'active', 'abc' => '123' }

// Loop through params
myUrl.searchParams.forEach((value, name) => console.log(`${name}: ${value}`));
// Returns id: 100
// status: active
// abc: 123

HTTP module

Create a basic server

HTTP With Nodejs

`const server = http.createServer((req, res) => {}` the req and res: Req is an object containing information about the HTTP request that raised the event. In response to the req event, you use res to send back an HTTP response. The req object has properties like url, method, headers, and query. One common thing is to get the name of the url making the request such as: `if (req.url === “/about”) {//dosomething}`

Here is an example serving up some JSON when a specific request is made to a certain url:

const http = require("http");
const path = require("path");
const fs = require("fs");

const server = http.createServer((req, res) => {
 if (req.url === "/api/user") {
    const users = [
      { name: "bob", age: 40 },
      { name: "John", age: 30 },
    ];
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(users));
  }
});

Note the users const being turned from a JS object into a string before being sent.