Node.js and Modules

Keywords: Javascript node.js Visual Studio Code

Components of JavaScript in browsers

JS in Browser

  • ECMAScript (Core Syntax) ES3 --> ES4 --> ES5 --> ES6 (2015) --> ES2016 --> ES2017.....

    • Variables, Constants

    • data type

    • function

    • Process control (if, switch, for, while,, continue, break)

    • operator

    • JS built-in objects (Array, String, RegExp, Date, Math....)

  • WebAPI (API provided by browser)

    • DOM (Document Object Model, document)

    • BOM (Browser Object Model, location, history,....)

    • XMLHttpRequest

    • Canvas

    • ...

Why JavaScript can be executed in browsers

Different browsers use different JavaScript parsing engines:

Chrome Browser=> V8

Firefox Browser=> OdinMonkey

Safri Browser=> JSCore

IE Browser=> Chakra (Chakra)


JavaScript Runtime Environment in Browsers

The V8 engine is responsible for parsing and executing JavaScript code.

The built-in API is a special interface provided by the runtime environment and can only be called in the runtime in which it belongs.

Introduction to Node.js

What Node.js can do

Based on Express/Koa framework ( Express - web Application Development Framework Based on Node.js Platform - Express Chinese Document | Express Chinese Network ), which allows you to quickly build Web applications

Based on Electron Framework ( Electron | Build cross-platform desktop apps with JavaScript, HTML, and CSS. ) to build cross-platform desktop applications

Based on the restify framework ( Restify ), which allows you to quickly build API interface projects

Read, write and manipulate databases, create useful command line tools for front-end development

What is Node.js

Node.js is a JavaScript runtime environment based on the Chrome V8 engine.

Popular understanding: Node.js provides the necessary environment for JavaScript code to run properly.

Official address: Node.jsNode.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Be careful:

Browsers are front-end environments for JavaScript.

Node.js is the backend runtime environment for JavaScript.

Browser built-in API s such as DOM and BOM cannot be invoked in Node.js.

Node.js Environment Installation

Download Installation

Get into Official Web (Chinese), you can see the following two versions:


LTS is a long-term stable version, LTS version is recommended for enterprise projects seeking stability.

Current is a fresh version of the new feature, and it is recommended that you install the current version of ode.js for users who are keen to try new features. However, there may be hidden bugs or security vulnerabilities in the current version, so it is not recommended to use the current version of ode.js in enterprise projects.

View the version number of installed Node.js

Open the terminal, after the terminal enters the command node-v, press the Enter key to see the version number of the installed Node.js.

Running JavaScript in the Node.js environment

Terminal Window Run

Operation steps:

Open any terminal, enter node command directly and return

Execute your JS code, press Enter to execute

Press "Ctrl+C" twice to exit.

Common problem

If there is an error running the node command in the vscode terminal, restart the vscode.

The path to execute the node must be

When executing files, you need to ensure that node xxx.js is in this format

node can only run JS code

Better not to use multiple terminals

Terminal Command

Execute JS file with node command node. /index.js

With the_key, you can quickly navigate to the last command executed
Fast path completion with tab key
Use the esc key to quickly empty the currently entered command
Enter cls command to empty terminal


What is modularity

Modularization is the process of splitting a large file into several small files, and also combining small files through specific syntax.

Modular Advantages

Better maintenance (for example, if the project needs to upgrade the login module, it won't affect other modules)

Better reusability (such as having a common function encapsulated. All other JS files can use this function)

Node specifies that each JS file is a small module. A project is composed of many small modules (JS files).

Understanding several modular specifications



CommonJS (Modularization in Node, using this scenario)


Node uses the CommonJS specification.

Classification of modules

Custom Module

In NodeJS, the JS files created are custom modules.

Built-in module

After installing Node, there are many built-in modules. We can load and use them directly.

Third-party modules

Modules written by others, published to npm website Up, we can download and use it.

Custom Module

Each JS file that we create is a custom module and has a module scope, that is, variables, constants, functions, and so on that are created in a module and can only be used in the current module.

Sharing (exporting/exporting) content for use by other modules requires exporting content using module.exports.

Module is a global object in Node that contains the details of the current module.

module.exports is the export of the module, which is used to export content. The default value is {}

Other modules, if you need to export using the above modules, can be loaded using require()

let result = require('module path')

For example, let test = require('./02-test');

Custom modules must be loaded with a path, even if. / they must be added. However, the suffix can be omitted.


02-test.js -- Export Content

let age = 30;
let name = 'laotang';
let height = '175cm';
let weight = '75kg';
let square = x => x * x;

// Export age, name, fn for use by other modules
module.exports = { age, name, square };

03-use.js -- Import Content

let test = require('./02-test');

console.log(test); // { age: 30, name: 'laotang', square: Function... }

What one module exports and what the other module gets when it loads.

Built-in module

Built-in modules are a set of basic APIs (function modules) that come with the Node.js platform. They are also called core modules.

path module

path is an API provided by Node itself and is designed to handle paths.


Loading modules

// Load the core module before using it
let path = require('path');
// perhaps
const path = require('path');

Call the method in the path module to handle the appropriate problem


const path = require('path');

// extname -- Get file suffix
console.log(path.extname('index.html')); // .html
console.log(path.extname('')); // .md

 join -- Smart Stitching Path
// ---------------------- Smart Stitching Path-----------------------------
 console.log(path.join('a', 'b', 'c')); // a/b/c

 console.log(path.join('a', 'b', 'c', 'index.css')); // a/b/c/index.css

// a has b in it, B has.. /c in it, meaning beyond words, C and B have the same level.
 console.log(path.join('a', 'b', '../c', 'index.js')); // a/c/index.js

// _u dirname always represents the absolute path of the current js file
console.log(path.join(__dirname, 'css', 'demo.css')); // /Users/tangfengpo/Study/123/Node01/code/css/demo.css

fs module

fs, file system, file system. This module can operate on files and folders


Loading modules

// Introducing modules, var, let can be used when introducing modules, but const is recommended because we don't want it to change
const fs = require('fs');

Methods to invoke the fs module, the common methods in the fs module are listed below

// readFile -- Read files asynchronously
fs.readFile('./test.json', (err, data) => {
    if (err) {
        console.log('Error reading file');
    } else {
        console.log(data); // Binary data read
        console.log(data.toString()); // Get raw data

fs.readFile('./test.json', 'utf-8', (err, data) => {
    if (err) {
        console.log('Error reading file');
    } else {
        console.log(data); // Raw data read
// writeFile -- writing files asynchronously
fs.writeFile('./abc.html', 'hello world', (err) => {
    if (err) {
        console.log('fail to write to file');
    } else {
        console.log('File Write Successfully');

querystring module

Modules for handling query strings (request parameters)

Usage method

Loading modules

const querystring = require('querystring');

Calling methods in the querystring module

// parse -- Parses a query string into a JS object
// { id: '1', name: 'zs', age: '20' }

// stringify -- Converts a JS object to a query string
console.log(querystring.stringify({ id: '1', name: 'zs', age: '20' }));
// id=1&name=zs&age=20

Built-in module - http module

http server processing module, you can use the http module to build the server

Steps to create a Web server

1. Import http core modules

2. Create a server object (the server object is responsible for establishing connections and receiving data)

3. Register the request event, set the function to handle the request when the browser sends the request to the server for execution

4. Listening Port (==This step can also be put before registering the request event==)

// 1.Load http module
const http = require('http');

// 2.Create a service object, typically named server
const server = http.createServer(); // create, server server

// 3.Register a request event for a server object to listen for browser requests. This event is triggered whenever there is a browser request
server.on('request', (req, res) => {
  // Set Response Status Code
  res.statusCode = 200;
  // Set Response Header
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  // Set Response Body
  res.end('hello,Welcome to the server, this is your response from the server');

// 4.Set Port, Open Service
server.listen(3000, () => {
  console.log('Server started');

req and res parameters

When a browser request is received, the request event is triggered, and the event handler has two form parameters, req and res.

req is the abbreviation of request, which is request. res is the abbreviation of response, which is response

Posted by rock_xl1 on Tue, 14 Sep 2021 19:09:30 -0700