Workspace
  • Study Book
  • WEB Network HTTP etc
    • Performance Optimization
    • Performance Optimization
    • HTTP/2 & SPDY
    • WebSocket
    • HTTP Header
    • Cross-Origin Resource Sharing
    • JSON, XML, other format
  • Javascript
    • Promise
    • make API call
    • Web API
    • Common JS
    • AJAX
    • Event DOM and delegation
    • ES6 new features
    • special function
    • function API
  • React
    • class component
    • Example
    • Lifting functions/ state up
    • Hot Loader
    • Testing
    • New Features
    • Hook
    • Simple code
    • Life Cycle
  • CSS
    • Horizontal & Vertical Align
    • GPU Animation
    • transform-function
    • LVHA Pseudo-classes
    • Selector
    • How To CSS
  • HTML
  • Redux
  • NodeJS
    • File System
  • express
    • express questions
    • express mongodb
  • Restful API
  • MongoDB
  • Compare
  • Test
    • Jest
  • Deploy development
  • coding question
  • DevOps
  • Webpack
  • GraphQL
Powered by GitBook
On this page
  • Node.JS
  • Event Loop
  • poll: poll new I/O, back to timer,
  • check: run setImmediate() callback, setImmediate() will add to check
  • close callback: run socket close callback
  • timers: run timer(setTimeout, setInterval)
  • I/O callback: run some remaining I/O callback
  • idle, prepare: node internal
  • REPL model
  • Express
  • NodeJS architecture
  • How to do auth in NodeJS
  • The advantages of NodeJS server
  • How to make HTTP request
  • How does NodeJS handle child threads
  • How does NodeJS support multi-processor platforms
  • File System
  • Util

Was this helpful?

NodeJS

REPL Node.js --Global Objects / util - Global Objects / util----File System / HTTP-----express,mocha,npm

PreviousReduxNextFile System

Last updated 2 years ago

Was this helpful?

Node.JS

// hello world
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Hello World!');
}).listen(8080);

Node.JS is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code server-side.

core is async I/O

Use async I/O not multi thread

like search: db.query('SELECT * from some_table', function(res) { res.output(); });

callback as second parameter. async -> event loop, solve the block

everything is event loop

Usage: node [options] [ -e script | script.js ] [arguments]

e.g.: node debug script.js [arguments]

Event Loop

allows Node.js to perform non-blocking I/O operations

the kernel tells Node.js so that the appropriate callback may be added to the poll queue to eventually be executed. We'll explain this in further detail later in this topic.

   ┌───────────────────────────┐
┌─>│           timers          │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │     pending callbacks     │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │       idle, prepare       │
│  └─────────────┬─────────────┘      ┌───────────────┐
│  ┌─────────────┴─────────────┐      │   incoming:   │
│  │           poll            │<─────┤  connections, │
│  └─────────────┬─────────────┘      │   data, etc.  │
│  ┌─────────────┴─────────────┐      └───────────────┘
│  │           check           │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
└──┤      close callbacks      │
   └───────────────────────────┘

poll: poll new I/O, back to timer,

if (poll queue is empty), {

if (has setImmediate), {poll will stop and go to check run this setImmediate.}

else: run callback, set timer

} else {

traverse queue, until is empty

}

check: run setImmediate() callback, setImmediate() will add to check

close callback: run socket close callback

timers: run timer(setTimeout, setInterval)

I/O callback: run some remaining I/O callback

idle, prepare: node internal

Micro Task vs Macro Task:

macro-task: setTimeout、setInterval、 setImmediate、script、 I/O

micro-task : process.nextTick、new Promise().then

setTimeout(()=>{
    console.log('timer1')
    Promise.resolve().then(function() {
        console.log('promise1')
    })
}, 0)
setTimeout(()=>{
    console.log('timer2')
    Promise.resolve().then(function() {
        console.log('promise2')
    })
}, 0)
复制代码

Browser:timer1=>promise1=>timer2=>promise2

node newest: timer1=>promise1=>timer2=>promise2

before node10 timer1=>promise1=>timer2=>promise2

REPL model

REPL stands for (READ, EVAL, PRINT, LOOP). NodeJS comes with bundled REPL environment. This allows for the easy creation of CLI (Command Line Interface) applications.

const repl = require('repl');

The repl module exports the repl.REPLServer class. While running, instances of repl.REPLServer will accept individual lines of user input, evaluate those according to a user-defined evaluation function, then output the result.

  • .break - When in the process of inputting a multi-line expression, entering the .break command (or pressing the <ctrl>-C key combination) will abort further input or processing of that expression.

  • .clear - Resets the REPL context to an empty object and clears any multi-line expression currently being input.

  • .exit - Close the I/O stream, causing the REPL to exit.

  • .help - Show this list of special commands.

  • .save - Save the current REPL session to a file: > .save ./file/to/save.js

  • .load - Load a file into the current REPL session. > .load ./file/to/load.js

  • .editor - Enter editor mode (<ctrl>-D to finish, <ctrl>-C to cancel).

Express

Express.JS is a web application framework for Node.JS. It is designed for building web applications and APIs.

NodeJS architecture

Single Threaded Event Loop Model

How to do auth in NodeJS

Using Passport.js. Passport is authentication middleware for NodeJS. Passport can be easily dropped into any Express-based web applications. It's a comprehensive set of strategies supports authentication using a username and password, Facebook, Twitter.

The advantages of NodeJS server

  • JavaScript as the programming language

  • Asynchronous events

  • Real-time web apps

  • NPM package manager

  • Data sharing

  • Event driven architecture

How to make HTTP request

  • Default http, https module

  • Request

  • Axios

  • SuperAgent

  • Got

http.get(options, (res) => {
  // Do stuff
}).on('socket', (socket) => {
  socket.emit('agentRemove');
});

How does NodeJS handle child threads

NodeJS is a single thread process. It does not expose child threads and thread management methods to the developer. Technically, NodeJS does spawn child threads for certain tasks such as asynchronous I/O, but these run behind the scenes and do not execute any application JavaScript code, nor block the main event loop. If threading support is desired in a NodeJS application, there are tools available to enable it, such as the ChildProcess module.

How does NodeJS support multi-processor platforms

Since NodeJS is by default a single thread application, it will run on a single processor core and will not take full advantages of multiple core resources. However, NodeJS provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster module is one of the core NodeJS modules and it allows running multiple NodeJS worker processes that will share the same port.

File System

To include the File System module, use the require() method.

  • Read files - fs.readFile()

  • Create files - fs.appendFile(), fs.open(), fs.writeFile()

  • Update files - fs.appendFile(), fs.writeFile()

  • Delete files - fs.unlink()

  • Rename files - fs.rename()

  • Upload files

Util

The util module is primarily designed to support the needs of Node.js' own internal APIs. However, many of the utilities are useful for application and module developers as well. It can be accessed using:

const util = require('util');
const util = require('util');

async function fn() {
  return 'hello world';
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  if (err) throw err;
  console.log(ret);
});