Node.js basic notes~~~

Introduction - learn node The purpose of JS is to help you open the black box of the server. Only by understanding the server can we better cooperate with the server developers in collaborative development

1.1 review and reflection

1. Why can javaScript be executed in the browser?

2. Why can javaScript operate DOM and BOM

3. javaScript running environment in browser

The running environment refers to the necessary environment for the normal operation of the code.

4. Can javaScript be used as the back end?

  • Yes, with the help of node JS can be implemented.

1, Why learn node js?

  • Enterprise demand

  • Experience in server development is better

  • Front end

  • Back end

  • Full stack Development Engineer (humorously say "all work")

    2, Node What is JS?

    (1) Node.js is a javaScript runtime environment (in short, node.js can parse and execute javaScript code)

    1.Node. javaScript running environment in JS

     

3, What can Node do

As a JavaScript running environment, Node only provides basic functions and API s. However, based on these basic capabilities provided by Node, many powerful tools and frameworks have sprung up one after another. Therefore, learning Node can make front-end programmers competent for more jobs and posts

  1. be based on Express framework , you can quickly build Web applications

  2. be based on Electron frame , you can build cross platform desktop applications

  3. be based on restify framework , you can quickly build API interface projects

  4. Read, write and operate the database, create practical command-line tools to assist front-end development, etc

4, Distinguish between LTS version and Current version

  1. LTS is a long-term stable version. For enterprise projects pursuing stability, it is recommended to install node of lts version js

  2. Current is an early version of new features. For users keen to try new features, it is recommended to install the current version of node js. However, there may be hidden bugs or security vulnerabilities in the current version, so it is not recommended to use the current version of node in enterprise projects js

5, What is a terminal

  1. Terminal (English: terminal) is specially designed for developers to realize human-computer interaction

  2. As a qualified programmer, it is necessary for us to remember some commonly used terminal commands to help us operate and use the computer better

    1.1 how to quickly open the terminal

    (1) In the folder address bar area, enter cmd and press enter.

    (2) Hold down the mouse shif and click the left mouse button to open the command window (powershell) here.

1.2 shortcut keys in the terminal

In the powershell or cmd terminal of Windows, we can improve the operation efficiency of the terminal through the following shortcut keys:

  1. Use the ↑ key to quickly navigate to the last executed command

  2. Use the tab key to quickly complete the path

  3. Using esc key can quickly clear the currently entered commands

  4. Enter the cls command to clear the terminal

6, fs file system

1. 1 FS file system module

1. The FS module is a node JS official module for operating files. It provides a series of methods and attributes to meet the user's needs for file operation

2.2 read the contents of the specified file

2.1 fs. Syntax format of readfile() (read content)

Parameter interpretation:

  1. Parameter 1: required parameter, string, indicating the path of the file

  2. Parameter 2: optional parameter, which indicates the encoding format to read the file

  3. Parameter 3: required parameter. After reading the file, get the reading result through the callback function

    2.2 judge whether the file is read successfully

    1. The result is null, indicating that the file was read successfully

    2. If it is not null, the file reading fails

const fs = require('fs')
fs.readFile('./files/1.txt','utf8',function(err,dataStr){
    if(err){
        return console.log('fail to read file'+err.message);
    }
    console.log('fail to read file'+dataStr);
})

2.3fs. Sample code for writefile() (write content)

Parameter interpretation:

3.3 judge whether the file is written successfully

const fs = require('fs')
fs.writeFile('./files/2.txt','abcdok',function(err){
    if(err){
        return console.log('File write failed'+err.message)
    }
    console.log(File written successfully);
})

4.4 fs sorting out test scores and cases

4.4.1 demand analysis

Use fs file system module to put the material in the directory txt file, sort out the test data to the score - OK txt file, before sorting out, score The data format in txt file is as follows:

Xiao Hong=99 Xiaobai=100 Xiao Huang=70 Xiao Hei=66 Little green=88

After finishing, the expected results are - OK The data format in TXT file is as follows:

Xiao Hong: 99
 Xiaobai: 100
 Xiao Huang: 70
 Xiao Hei: 66
 Little green: 88

4.4.2 implementation steps

1. Read the score file

const fs = require('fs')//Import fs module
//Call FS Readfile() reads the contents of the file
fs.readFile('./files1/achievement-ok.txt','utf8',function(err,dataStr){
    //Judge whether the reading is successful
    if(err){
        return console.log('fail to read file'+err.message)
    }
    console.log('Read file successfully'+dataStr)
})

2. Processing results

const fs = require('fs')//Import fs module
//Call FS Readfile() reads the contents of the file
fs.readFile('./files1/achievement-ok.txt','utf8',function(err,dataStr){
    //Judge whether the reading is successful
    if(err){
        return console.log('fail to read file'+err.message)
    }
   //1. Divide the score data according to the space
   const arrOld = dataStr.split('')
 
   //2. For the circularly divided array, replace the string for each item of data
   const arrNew = []
   arrOld.forEach(item =>{
       arrNew.push(item.replace('=',':'))
   })
   //3. Merge each item in the new array to get a new string
    const newStr = arrNew.join('\r\n')
    console.log(newStr);
})

3. Write the sorted results into a new file

const fs = require('fs')//Import fs module
//Call FS Readfile() reads the contents of the file
fs.readFile('./files1/achievement-ok.txt','utf8',function(err,dataStr){
    //Judge whether the reading is successful
    if(err){
        return console.log('fail to read file'+err.message)
    }
   //1. Divide the score data according to the space
   const arrOld = dataStr.split('')
 
   //2. For the circularly divided array, replace the string for each item of data
   const arrNew = []
   arrOld.forEach(item =>{
       arrNew.push(item.replace('=',':'))
   })
   //3. Merge each item in the new array to get a new string
    const newStr = arrNew.join('\r\n')
   //4. Call FS The WriteFile () method writes the processed results into a new file
   fs.writeFile('./files1/achievement-ok.txt',newStr,function(err){
       if(err){
           return console.log('fail to write to file'+err.message)
​
       }
       console.log('Score writing score');
   })
})

VII fs path problem

1. The problem of FS module path dynamic splicing

When using fs module to operate files, if the operation path provided is in/ Or/ When the relative path at the beginning of the path, it is easy to have the problem of path dynamic splicing error

Reason: when the code is running, it will dynamically splice the complete path of the operated file according to the directory where the node command is executed

Solution: when using fs module to operate files, directly provide the complete path instead of providing it/ Or/ The relative path at the beginning, so as to prevent the problem of path dynamic splicing

  1. Replace relative path with full path

    In js, \ stands for referral and \ \ stands for slash

    The relative path is replaced by the complete path, but this writing method has poor portability and is not conducive to later maintenance

    const fs = require('fs')
    ​
    fs.readFile('C:\\Users\\Lenovo\\Desktop\\code.js Basics\\node.js first day\\files1\\1.txt','utf8',function(err,dataStr){
        if(err){
            return console.log('Failed to get file'+err.message)
        }
        console.log('Get file successfully'+err.message)
    })
    1. Use__ dirname solves the problem of path splicing

      __dirname attribute Node A global attribute provided to indicates the directory where the current file is located
      
      const fs = require('fs')
      ​
      // __ The dirname attribute solves the problem of path splicing
      fs.readFile(__dirname + '/files1/1.txt', 'utf8', function (err, data) {
        // Determine whether the err object is null
        if (err) {
          return console.log('File read failed:', err.message)
        }
      ​
        console.log('The file was read successfully. The contents are:', data)
      })

8, path module

1. What is the path module

  1. The path module is node JS official module for processing paths. It provides a series of methods and attributes to meet the processing needs of users for paths, such as:

    • path. The join () method is used to splice multiple path fragments into a complete path string

    • path. The basename () method is used to parse the file name from the path string

2. If you want to use the path module to process the path in JavaScript code, you need to import it first in the following way

const path = rquire('path')

2.path. Syntax format of join()

Use path The join () method can splice multiple path fragments into a complete path string. The syntax format is as follows

path.join([...paths])

.. / has the function of offsetting the previous path, one/ There is no such function

  1. path. Syntax format of basename()

    Use path Basename () method can obtain the last part of the path. This method is often used to obtain the file name in the path. The syntax format is as follows

 path.basename(path[,ext])

Parameter interpretation:

  1. Path < string > required parameter, which represents the string of a path

  2. Ext < string > optional parameter, indicating the file extension

  3. Return: < string > indicates the last part of the path

1.1 path. Code example for basename()

Use path Basename() method, you can get the name part of the file from a file path

2.2path. Syntax format of extname()

path.extname(path)

Parameter interpretation:

  1. Path < string > required parameter, indicating the string of a path

  2. Return: < string > returns the obtained extension string

3.path. Code example for extname()

 

Keywords: Javascript node.js MySQL JSON MongoDB

Added by TempleDMDKrazd on Sun, 30 Jan 2022 01:45:40 +0200