[front end notes] nodejs introduction learning notes (CommonJS version)

The version number of node stable version is even
Now node is supported by default


In Node, a js file is a module
Each variable in the js module can be accessed independently of the other variables in the js module. Therefore, it is not possible to prevent the repetition of a function in the js module
exports exposes properties and methods externally
For introducing module require

In Node, module represents the current module. When customizing a module, you can use module Exports shares the members in the module. When you import a custom module with the require() method, you get the module Objects pointed to by exports

//Usually, the default exports in Node is the attribute of module, that is, exports points to module by default Exports is an object that can be accessed through ` exports Property to set module exports
//However, when you directly assign a value to exports, the object pointed to by exports will change, not module Exports is the object. At this time, exports cannot be received outside
exports.a = "xxx" //This assignment is to set module exports
exports = {a:"xxx"} //This assignment will change the direction of exports and no longer point to the module in the heap memory Instead, it points to {a:"xxx"} in the heap memory
module.exports = {a:"xxx",b:"yyy"}//You can directly set the exposed objects of the module in this way

Core module

Modules provided by the node engine
The identification of the core module is the name of the module

var fs = require("fs")
var express = require("express")

Node when introducing a module with a module name, it will first be in the node of the current directory_ Find out whether the module is included in modules. If yes, use it directly. If not, go to the node of the upper directory_ Search in modules. If you don't search in the upper directory until you find the root directory of the disk. If you still don't, an error is reported

File module

Modules created by users themselves
The representation of the file module is the path of the file (absolute path, relative path)
Relative path usage Or start with

var router = require("./router")


There is a global object global in node, which is similar to window in web pages. Variables created in the global will be saved as global attributes, and functions created in the global will be saved as global methods
arguments.callee saves the currently executed function object, which can verify that all nodes are in the function.
When node executes the code in the module, it will first add the following code at the top of the code:



Package structure

Used to organize various files in the package
The package is actually a compressed file, which is decompressed and restored to a directory. The directory conforming to the specification shall contain the following files:

- package.json Description file(must)
- bin Executable binary(Optional)
- lib js code(Optional)
- doc file(Optional)
- test unit testing (Optional)

Package description file package json

Describe the relevant information of the package for external reading and analysis
Package description file is used to express non code related information. It is a json format file package json, located in the root directory of the package, is an important part of the package
package. Fields in JSON
Note: package Comments cannot be written in JSON

name name
description describe
version edition
keywords keyword(For searching packages)
maintainers Major contributors
contributors Who submitted the code
bugs Submit bug Address of
licenses agreement
repositories Warehouse address
dependencies rely on
homepage homepage
os system
engine engine
builtin Build tools

Package manager npm(Node Package Manager)

NPM helps node complete the release, installation and dependency of third-party modules. With the help of NPM, a good ecosystem is formed between node and third-party modules

NPM command

npm init initialization npm(You can create one package.json (file)
npm -v View version
npm Help description
npm search Package name search module package
npm install/i The package name installs the package in the current directory
npm install/i Package name -g Global mode installation package (Globally installed packages are generally tools)
npm install/i Package name --save Install package and add to dependency
npm install Download the package that the current project depends on
npm remove/r Package name delete package

cnpm configuration

Search engines directly search cnpm or: Direct jump

node Foundation

Buffer (buffer)

  1. The structure of Buffer is very similar to that of array, and the operation method is also similar to that of array
  2. Binary files cannot be stored in the array, but Buffer is specially used to store binary data
  3. You do not need to import modules to use Buffer. You can use it directly
    var str = "abcdefg"
    var buf = Buffer.from(str)//Convert a string to buffer
  4. Binary data is stored in the Buffer, but it is displayed in hexadecimal, so what you see when outputting is hexadecimal
  5. The range of each element in Buffer is from 00-FF to 0-255
    A 0 or a 1 in a computer is called a bit
    8 bit = 1 byte
    1024byte = 1kb
    1024kb = 1mb
    1024mb = 1gb
    1024gb = 1tb
    An element in buffer, which occupies one byte of memory
    Buffer constructors are not recommended
    Once the size of the buffer is determined, it cannot be modified (buffer is actually a direct operation on the underlying memory, and the memory space created by the buffer must be continuous)
    //Create a 10 byte buffer
    var buf = Buffer.alloc(10);
    buf[0] = 88;
    buf[1] = 255;//This is already the maximum value
    buf[2] = 0xaa;
    buf[10] = 15;
    console.log(buf[2])//The output is 170. As long as it is a number, the output on the console must be hexadecimal
    console.log(buf[2].toString(16))//This can be converted to hexadecimal
    console.log(buf[2].toString(2))//This can be converted to binary
  6. Buffer.alloc(size)
    Create a buffer of specified bytes. This method will clear the contents of the memory and then create a buffer in the memory
  7. Buffer.allocUnsafe(size)
    Create a buffer of specified bytes. This method will not clear the contents of memory, so it may not be empty at the beginning after creation, and may contain sensitive data, but the performance is better than the previous one
  8. Buffer.from(str) converts a string to buffer

fs (file system)

Operating system files through node
To use fs, you need to introduce the fs module var fs = require("fs")

  1. Synchronous file writing
    fs.openSync(path,flags[,mode]) opens the file

    - path File path to open
    - flags Type of operation to do when opening a file
      - r read-only 
      - w Writable
    - mode Set the operation permission of the file, which is generally not transferred

    The return value is a number, indicating that the file descriptor is opened
    var fd = fs.openSync("hello.txt",w);
    fs.writeSync(fd,string[,position[,encoding]]) writes content to the file

    - fd File descriptor, the descriptor of the file to be written
    - string What to write
    - position Start of write
    - encoding Code written, default utf-8

    fs.closeSync(fd) closes the file

  2. Asynchronous file writing
    fs.open(path,flags[,mode],callback) opens the file

    - path File path to open
    - flags Type of operation to do when opening a file
      - r read-only 
      - w Writable
    - mode Set the operation permission of the file, which is generally not transferred
    -callback Callback function, cannot be omitted

    The results of asynchronously called methods are returned through callback function parameters
    The callback function has two parameters:

    - err Error object, if there are no errors; otherwise null
    - fd File descriptor

    fs.write(fd, string[, position[, encoding]], callback) file write

    var fs = require("fs");
            fs.write(fd,"Ha ha ha ha ha ha ha",(writeErr)=>{
                   console.log("Write successful")
                        console.log("Close file")
  3. Simple file write

    - file The path of the file to operate on
    - data Data to write
    - options Option, you can make some settings for writing
    - callback Function executed after writing


    var fs = require("fs");
    fs.writeFile("test.txt","adopt writeFile Written content".{flag:"w"},function(err){
        console.log("Write successful");

    The open state of the file

    r Read the file. If the file does not exist, an exception occurs
    r+ Read and write the file. If the file does not exist, there will be no exception
    rs Open files for reading in synchronous mode
    rs+ Open files for reading and writing in synchronous mode
    w Open the file for write operation. If it does not exist, create it. If it exists, truncate it
    wx The open file is used for write operation. If it exists, the open fails
    w+Open the file for reading and writing. If it does not exist, create it. If it exists, truncate it
    wx+ Open the file for reading and writing. If it exists, the opening fails
    a Open the file for appending and create it if it doesn't exist
    ax Open the file for appending. If it exists, it fails
    a+Open the file for reading and appending, and create it if it does not exist
    ax+Open the file for reading and appending. If it exists, it fails
  4. Simple file reading

    - path File path to read
    - options Read options
    - callback(err,data) Callback function, through which the content is read and returned


    var fs = require("fs");
            console.log("Write file succeeded")
  5. Streaming file writing
    It is applicable to some relatively large files and can be written to files multiple times
    fs.createWriteStream(path[,options]) creates a write stream

    - You can create a writable stream
    - path,File path
    - options Configured parameters

    Listen for the open and close events of the stream to listen for the opening and closing of the stream

    on(Event string,Callback function)
    - You can bind an event to an object
    once(Event string,Callback function)
    - You can bind a one-time event to an object, which will automatically expire after being triggered once


    var fs = require("fs");
    var ws = fs.createWriteStream("test.txt");
    ws.once("open", function () {
        console.log("The stream is open");
    ws.write("This is a write sssss Content 2")
    //Close stream, cannot use WS Close, because the close will be closed before the transmission is finished. Use end() to close after the transmission is finished
        console.log("The flow is closed")
  6. Streaming file reading

    var fs = require("fs");
    var rs = fs.createReadStream("test.txt");
    var ws = fs.createWriteStream("testWrite.txt");
    //Opening and closing of monitoring stream
      console.log("The read stream is open")
      console.log("The read stream is closed")
      ws.end()//After reading the stream, close the writable stream
      console.log("The write stream is open")
      console.log("The write stream is closed")
    //After listening and reading, you can only listen to data, and use on, because it is continuous listening

    Simpler example

    var fs = require("fs");
    var rs = fs.createReadStream("test.txt");
    var ws = fs.createWriteStream("testWrite.txt");
    //pipe() can output the contents of the readable stream directly to the writable stream
  7. Verify that the path exists FS existsSync(path)

  8. Get file information
    fs.stat(path,callback) gets file status asynchronously
    The callback function has two parameters err and stats
    stats is an object that holds file information

  9. Delete file

  10. List files
    The callback function has two parameters err and files
    Files is a list of folders / files, which is an array

  11. truncate file
    Changing the file to the specified size will truncate

  12. create directory

  13. Delete directory

  14. Rename files and directories

    - oldPath Old path
    - newPath New path
    - callback Callback function


  15. Monitor file changes and writes

    - filename The name of the file to monitor
    - options configuration option
    - listener Callback function. When the file changes, the callback function will execute
      There are two parameters in the callback function
      - curr Status of the current file
      - prev Status of the file before modification
      (Both objects are stats object)

Keywords: Javascript Front-end prototype

Added by Transwarp-Tim on Tue, 08 Mar 2022 10:38:53 +0200