I. Introduction to Node

1. What node does

  • Run JS out of the browser
  • Write background API interface
  • Webpack and NPM both run on Node
  • Middle layer: The middle layer server that is responsible for I/O reads and writes

2. Environment construction and operation

  • The official website: nodejs.org/zh-cn/
  • Check the installation version: Node -v
  • Quick open file command line window: Shift + right click – “select here to open powerShell window;
  • Run js file command: node index.js(filename)

3. NPM package management

Manage third-party modules, plug-ins, libraries, etc.

  • Initialization: NPM init
  • NPM install XXX/NPM I XXX
  • Delete: NPM uninstall XXX/NPM UN XXX
  • NPM install CNPM -g — name =registry.npm.taobao.org

2. Node module

1. Global module

The Process object is a global variable that provides information about and controls the current Node.js process. It can be accessed anytime, anywhere, without reference.

  • Process. env(environment variable)
  • Process. Argv (parameters)

2. System module

Require (), but don’t download it separately.

  • The path module provides utilities for handling file and directory paths. It can be accessed in the following ways:
const path = require('path');
Copy the code

Path. dirname: Returns the directory path of the current file.

console.log(path.dirname('/a/b/1.jpg')); / / "/ a/b"Copy the code

path.resolve()

console.log(path.resolve('/nodeJS/a/b/c','.. /',"d")); / / "/ nodeJS/a/b/d" / / get the absolute path to the file path. The resolve (__dirname, 'index. Js)Copy the code
  • Fs is used for file read and write operations
const fs = require('fs'); / / read the fs. ReadFile ('/a.t xt ', (err, data) = > {the if (err) {the console. The log (err); }else{ console.log(data.toString()); }}) / / modify the fs. WriteFile ('/a.t xt ', 'write ha ha ha ha, (err) = > {the if (err) {the console. The log (err); }}) / / additional (update) the fs. WriteFile ('/a.t xt ', 'write ha ha ha ha 1, {flag:' a '}, (err) = > {the if (err) {the console. The log (err); }})Copy the code

3. Custom modules

Require () encapsulates its own module

  • exports

Exports are only available. Syntax exposes internal variables. Such as: exports. = XXX XXX

exports.a=1
exports.b=1
Copy the code
  • Module, batch export

Module.exports = XXX module. Exports = XXX module. Exports = XXX

module.exports={
    a:1,b:2
}
Copy the code
  • require

If there is a path, go to the path to find; If not, go to node_modules; Go to node_modules, the node installation directory.

let mod1=require("./module1")
console.log(mod1);
Copy the code

Data requests in Node

The HTTP module

  • get

Get the data, which is transferred in the URL. Small capacity

  • post

The data is transferred in the body

Reference: www.imooc.com/video/20552

Juejin. Cn/post / 684490…