NodeJs

From bibbleWiki
Jump to navigation Jump to search

Setup

Running start up scripts in node

"scripts": {
  "start": "run-p start:dev start:api",
  "start:dev: "webpack-dev-server --config webpack.config.dev.js --port 3000",
  "prestart:api": "node tools/createMockDb.js",
   "start:api": "node tools/apiServer.js"
};

The run-p runs multiple jobs, pre<value> runs the command before the value without pre

Adding consts in webpack

To pass dev/production consts we can do this using webpack. Include webpack in you webpack.config.dev.js and webpack.DefinePlugin e.g.

const webpack = require("webpack")
...
plugins: [
    new webpack.DefinePlugin({
        "process.env.API_URL": JSON.stringify("http:://localhost:3001")
    })
],
...

Introduction

Node is popular because

  • Node supports JavaScript
  • Non Blocking
  • Virtual Machine Single-Thread

There is a site https://medium.com/edge-coders/how-well-do-you-know-node-js-36b1473c01c8 where u can test your knowledge.

Closures

I am really bad at remembering names for things for here is my understanding of Closures

Lexical Scoping

Basically this is driving at the fact there is such a time called scope, maybe new to people in JS at one time. ha ha. I.E. the var is available in init() but not outside of init()

This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();

Closure Example

And repeat this almost, is that we return the function to be executed later. The values at the time of calling makeFunc are retained. i.e. name is 'Mozilla' if we execute myFunc().

A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created. In this case, myFunc is a reference to the instance of the function displayName that is created when makeFunc is run. The instance of displayName maintains a reference to its lexical environment, within which the variable name exists.

function makeFunc() {
  var name = 'Mozilla';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();