What is the node. Js

Node.js is not any language, but a JavaScript runtime based on the Chrome V8 engine.

Noun explanation

  • Chrome V8 engine:

    • Chrome: indicates the Chrome browser

    • Engine: A tool for parsing and executing code.

      An engine converts fuel into power; The JS parsing engine can translate the code into the final result

    • V8: Project code name

  • Runtime: Understood as a container, the environment in which code is run.

The installation of the node

You are advised to install the long-term stable version of 14.17.6 on the official website (search node.js on Baidu).

The use of the node

After node is installed, there are no shortcuts on the desktop.

Windows quick open terminalThree ways:

  1. CMD window (window+R, –> run –> enter CMD, enter)

  1. In the address bar of Explorer, entercmdPress Enter to open the terminal
  2. Shift + right click anywhere

Quick way to open a terminal on a Mac:

① Use Command(⌘) + space to open the search window

② Enter Terminal in the search window and press Enter to open the terminal

Vscode’s own way to open the terminal

Simple keyboard keys and commands

Copy and paste

Copy content in the small black window: select the content, then click the right mouse button

Copy the contents of the paste board to the small black window: right-click the mouse

Run the code in Node.js

Please prepare a JS file in advance. For example, the path is d:/ SRC /index.js

The details are as follows:

// d:/src/index.js

var a = 1;

console.info(a + 2); Open the terminal under the directory of the file, as shown in the figure:

Run this file

format

Node is followed by the path of the file to be executed, such as the node file nameCopy the code

Note: Node has a space after it

Module classification in Node.js

  • The core module

    • Nodejs is a built-in module. You can use nodeJS directly after installing it. It is equivalent to the functions such as alert and confirm used when learning JS.

    Core modules are nodes’ built-in modules, which are ready to use out of the box after Nodejs is installed

  • Each core module has unique identifier name (fs, path, the querystring, HTTP…)

  • There are many core modules, and each module has its own function, which is documented here.

  • Use steps are the first entry, then use

    Const fs = require(‘fs’)

const path = require('path') // 1. Import module const STR = path.join('a', 'b') // 2. Use the module console.log(STR). Each core module has its own functionality, and you can import whichever you want. ** Syntax **Copy the code

Receive name of const module = require(‘ module name ‘)

1. The receiving name of the module can be customized, as long as it is a valid variable name. Such as:Copy the code

Const 123fs = require(‘fs’) // error, cannot start with a number

Const p = require(‘path’) // Correct

2. Const. We can use var, let, but we recommend using const because we don't want it to be changed. The name doesn't have to be capitalized FS, it's usually just the name FS.Copy the code

Fs Module Introduction

Fs module (fs is short for FileSystem) is the module used by Node.js to perform file operations. It belongs to the core module. Once you’ve introduced it, you can use it.

Official manual: nodejs.cn/api/fs.html api.nodejs.cn/

Steps to use the FS module

  1. The introduction of the module

    Const fs = require('fs'); // We can use var and let, but we recommend using const because we don't want it to be changed. // The name does not need to be capitalized as FS.Copy the code
  2. Call the API to implement specific requirements

    Fs.xxx () // where XXX refers to an APICopy the code

    Fs is a core module dedicated to manipulating files

    The role of readFile

    Reading file contents

format

Description:

  • Parameter 1: file path. Both relative and absolute paths work.

  • Parameter 2: indicates the configuration item. It is used to configure character sets. The value can be utf8. If this parameter is not specified, the file content is returned as a Buffer.

  • Parameter 3: callback function. This callback function is automatically called after reading the file, passing in err and data

    • If the read succeeds, the two arguments in the callback function are:

      • err: null

      • Data: indicates the file content. If parameter 2 is not set, binary data is returned. You can use the toString() method to encode binary data

        Convert to a normal string

    • If the read fails, the two arguments in the callback are:

      • Err: error object
      • data: undefined

      Example 1: Read text content

The directory structure

-1.txt # text file -01.readfile.js # code used to read the contents of 1.txtCopy the code

const fs = require("fs")
fs.readFile('1.txt',(err, data) => {
  console.log(data);
});
Copy the code

The data above will be a Buffer object, similar to an array.

  • Its elements are hexadecimal two-digit numbers, which represent the binary format of the file’s contents in the computer.
  • It has a toString() method that can be used to convert content to a string in UTF-8 format.

Example 2: Read text content – specify encoding format


const fs = require("fs")
fs.readFile('1.txt', "utf8", (err, data) => {
  console.log(data);
});
Copy the code

Example 3: Reading in a picture file


const fs = require("fs")
fs.readFile('./img/1.jpg',  (err, data) => {
  if (err) throw err;
  console.log(data);
});
Copy the code

Lesson learned: Not all files should be converted to strings

Example 4: Effect of asynchrony

asynchronous

Const fs = require("fs") console.log(1) fs.readFile(' file path ', "utf8", (err, data) => {if (err) throw err; console.log(data); }); console.log(2)Copy the code

Fs module -readFile- Observe and handle errors

fs.readFile(’00.text’,’utf8′, (err, data)=>{ if(err) { console.log(‘err’, err) return }

// If there is an error in the process of reading, err is an error. If there is no error, err is null. // console.log('err', err) console.log('data', data) after an error is encountered in Node.js, you should observe the error description. ` ` `Copy the code

Fs module -writeFile- File write

writeFile

Function: Writes a string to a specified file.

Features:

- If the file does not exist, it will try to create the file - it is an overwrite: it will delete the contents of the source file and fill in the current contentsCopy the code

Format:

Fs. writeFile(pathName, Content, Option, (err) =>{}); // Parameter 1: the file path to be written -- relative path and absolute path are both acceptable. Absolute path is recommended. // Parameter 2: the content of the file to be written, which is a string or Buffer format. The callback that is triggered after the write is complete takes one parameter, err.Copy the code

Example 1: Write a plain string

const fs = require(‘fs’) fs.writeFile(‘./a.txt’, ‘hello world! \n Change line ‘, err => {if (err) {console.info(err)}})

## Note: Newline is \n

Example 2: Writing JSON data

To raise the question a bit, ask: How do I write data to a file?

Const fs = require('fs') const data = [{name: '小王', age: 20}] fs.writeFile('./a.txt', data, err => { if (err) { console.info(err) throw err } })Copy the code

The above is incorrectly written: data is not a string or Buffer

The correct way to do this is to use JSON.

Const fs = require('fs') const data = [{name: '小王', age: 20}] fs.writeFile('./a.txt', JSON.stringify(data), err => { if (err) { console.info(err) } })Copy the code

Fs module -appendFile- File is appended to write

function

Writes a string (append write) to the specified file, or tries to create it if it does not exist.

format

fs.appendFile(pathName, content, option, callback); // Parameter 1: the file path to be written -- relative path and absolute path are both acceptable, absolute path is recommended // Parameter 2: the string to be written to the file // Parameter 3: configuration item, set the character set to be written, default UTF-8 // Parameter 4: The callback that is triggered after the write is complete takes one parameter, err.Copy the code

The sample

Const fs = require('fs') fs.appendFile('./a.txt', '\n ', err => {if (err) {console.info(err) throw err}})Copy the code

\ N: indicates a new line

Path problem – Get absolute path

__dirname,__filename

__filename and __dirname are global variables built into Node.js

  • Features: no declaration can be used directly

  • The meanings of global variables are:

    • Variables: Their values change. The value varies from file to file.
    • Global: Can be used directly anywhere.
  • Among them:

    __filename Indicates the full path of the current file (including the filename)

    __dirName indicates the full directory where the current file is stored (excluding the filename)

Test use, anywhere in any code


console.log(__dirname)
console.log(__filename)
Copy the code

When operating on files, use absolute paths

Just concatenate before the path when reading in the file:

Console. log(__dirname) const fs = require('fs') // 2) add html5.jpg const filePath = __dirname + '\html5.jpg' Console. log(filePath) // 3) Read fs.readFile(filePath,function(err, data) { if(err) { console.log(err) return } console.log(data) })Copy the code

Path module – Basic use

role

Path is also the core module in Node, and is used to handle path problems: concatenation, parsing, suffixing, and so on.

The document address

Using the step

  1. The introduction of the module

const path = require('path')
Copy the code
  1. Use the module

The commonly used API

  • Path.basename () : This method returnspathThe last part. Generally used to get the file name in the path.
  • Path.join (): joins paths
  • Path.extname (): obtains the suffix name

The sample

path.basename('/foo/bar/baz/asdf/quux.html'); / / return: 'quux. HTML' path. The basename ('/foo/bar/baz/asdf quux. HTML ', 'HTML'); / / return: 'quux' path. The dirname ('/foo/bar/baz/asdf quux "); // Returns: '/foo/bar/baz/asdf' path.extname('index.html'); // Return: '.html'Copy the code

Note: we don’t care if the address actually exists, just call the method and get the result.

Path module – Optimizes path spelling in file reading and writing

The core code

Path. join(__dirname, 'file relative address ')

The sample

// add html5.jpg const fs = require('fs') const path = // require('path') const filePath = path.join(__dirname, 'html5.jpg') // const filePath = __dirname + '\html5.jpg' // Console. log(filePath) fs.readFile(filePath,function(err, data) { if(err) { console.log(err) return } console.log(data) })Copy the code