---
description: >-
  REPL Node.js --Global Objects / util  - Global Objects / util----File System /
  HTTP-----express，mocha，npm
---

# NodeJS

## 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

![](https://4116032991-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LgnugJ0SdX2tMAwP37V%2F-LhwPqE2hmPnHhfX83Qz%2F-LhwQ0E2YNvrt3axhSbZ%2Fimage.png?alt=media\&token=69aee5a6-c218-43a5-b35e-4475a5495c09)

Usage: node \[options] \[ -e script | script.js ] \[arguments]&#x20;

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,**  &#x20;

if (poll queue is empty), {&#x20;

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

&#x20;    else: run callback, set timer

} else {

&#x20; 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`

![](https://4116032991-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LgnugJ0SdX2tMAwP37V%2F-Li-Drnx_eEQdvflYV3P%2F-Li-EAicnK9uBNYQM1eo%2Fimage.png?alt=media\&token=640a136e-1ea6-4847-9779-898b28114802)

![](https://4116032991-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LgnugJ0SdX2tMAwP37V%2F-Li-Drnx_eEQdvflYV3P%2F-Li-EJnaEsmKGPWlAJUJ%2Fimage.png?alt=media\&token=7888d29e-772d-4ae8-b913-0c1619a59bd8)

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.&#x20;

```
const repl = require('repl');
```

The `repl` module exports the [`repl.REPLServer`](https://nodejs.org/api/repl.html#repl_class_replserver) class. While running, instances of [`repl.REPLServer`](https://nodejs.org/api/repl.html#repl_class_replserver) will accept individual lines of user input, evaluate those according to a user-defined evaluation function, then output the result.&#x20;

* `.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&#x20;

Single Threaded Event Loop Model&#x20;

## 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.&#x20;

## 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.&#x20;

## 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.&#x20;

## 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);
});
```
