Get to know node JS (fs/path/http module)

1. Get to know node js

1. What is a node js

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

Node.js official website address: https://nodejs.org/zh-cn/

.2. Node. JavaScript running environment in JS

.3. Node. What can JS do

       Node. As a JavaScript running environment, JS only provides basic functions and API s. However, based on node JS provides these foundations, and many powerful tools and frameworks have sprung up one after another, so I learned node JS, which can make front-end programmers competent for more jobs and positions:

① Based on Express framework( http://www.expressjs.com.cn/ ), you can quickly build Web applications

② Based on Electron framework( https://electronjs.org/ ), you can build cross platform desktop applications

③ Based on Restify framework( http://restify.com/ ), you can quickly build API interface projects

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

4. Node.js environment installation

If you want to use node JS to run Javascript code, you must install node on your computer JS environment.

The installation package can be downloaded from node The homepage of the official website of JS can be directly downloaded and entered into node JS official website home page( https://nodejs.org/en/ ), click the green button, download the required version, and then double-click to install directly.

Open the terminal, enter the command node – v in the terminal, and press enter to view the installed node JS version number.

2. fs file system module

2.1 what is the fs file system module

The fs module is a node JS official module for operating files. It provides a series of methods and attributes to meet the needs of users for file operation.

2.2 read the contents of the specified file

2.2.1. fs. Syntax format of readfile()

//1. Import fs module to operate files
const fs = require('fs')

//2. Call FS The readfile() method reads the file
//Parameter 1: read file storage path
//Parameter 2: the encoding format used when reading the file. Generally, utf8 is set by default
//Parameter 3: callback function, get the result of reading failure and success, err dataStr
fs.readFile('./files/1.txt','utf8',function(err,dataStr){
//2.1 printing failure results
   //If the read is successful, the value of err is null
    //If the reading fails, the value of err is the wrong object and the value of dataStr is undefined
    console.log(err);
    //2.2 printing successful results
    console.log(dataStr);
})

 2.2.3. Judge whether the file is read successfully

You can judge whether the err object is null, so you can know the result of file reading:

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

2.3 write content to the specified file

2.3.1. fs. Syntax format of writefile()

Use FS The writefile() method can write content to the specified file. The syntax format is as follows:

// 1. Import fs file system module
const fs = require('fs')
// 2. Call FS The writefile() method writes the contents of the file
// Parameter 1: indicates the storage path of the file
// Parameter 2: indicates the content to be written
// Parameter 3: callback function
fs.writeFile('./files/3.txt', 'ok123', function(err) {
  // 2.1 if the file is written successfully, the value of err is equal to null
  // 2.2 if file writing fails, the value of err is equal to an error object
  // console.log(err)
  if (err) {
    return console.log('File writing failed!' + err.message)
  }
  console.log('File written successfully!')
})

Will be generated automatically/ files/3.txt this file

3.path module

3.1 what is the path module

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.

3.2.2. path. Code example for join()

Use path The join () method can splice multiple path fragments into a complete path string:

const path = require('path')
const fs = require('fs')

// Note:/ Offsets the previous path
const pathStr = path.join('/a', '/b/c', '../../', './d', 'e')
console.log(pathStr)  //\a\d\e
//fs.readFile(__dirname + '/files/1.txt')
fs.readFile(path.join(__dirname, '/files/1.txt'), 'utf8', function(err, dataStr) {
  if (err) {
    return console.log(err.message)
  }
  console.log(dataStr)
})

Note: in the future, all operations involving path splicing should use path The join () method. Do not use + to splice strings directly

3.3 get the file name in the path

3.3.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

3.4.1. path. Syntax format of extname()

Use path Extname() method to obtain the extension part in the path,

4. http module

4.1 what is the http module

The http module is node JS official module for creating web server. http provided through the http module Createserver () method can easily turn an ordinary computer into a web server, so as to provide external web resource services.

Every Web server in the Internet has its own IP address

  • During the development period, your computer is both a server and a client. In order to facilitate the test, you can enter the IP address 127.0.0.1 in your browser and access your computer as a server
  • During the development and testing, the domain name corresponding to 127.0.0.1 is localhost. They all represent our own computer, and there is no difference in the use effect.

 4.4.1. Basic steps for creating a web server

// 1. Import http module
const http = require('http')
// 2. Create a web server instance
const server = http.createServer()
// 3. Bind the request event for the server instance and listen to the client's request
server.on('request', function (req, res) {
  console.log('Someone visit our web server.')
})
// 4. Start the server
server.listen(8080, function () {  
  console.log('server running at http://127.0.0.1:8080')
})

4.4.5. req /res request / response object

const http = require('http')
const server = http.createServer()
// req is a request object, which contains data and attributes related to the client
server.on('request', (req, res) => {
  // req.url is the URL address requested by the client
  const url = req.url
  // req.method is the method type requested by the client
  const method = req.method
  const str = `Your request url is ${url}, and request method is ${method}`
  console.log(str)
  // Call the res.end() method to respond to some content to the client
  res.end(str)
})
server.listen(80, () => {
  console.log('server running at http://127.0.0.1')
})

4.4.7. Solve the problem of Chinese garbled code

When calling res.end() method to send Chinese content to the client, there will be garbled code. At this time, you need to manually set the encoding format of the content:

// Call res.setHeader() method and set the content type response header to solve the problem of Chinese garbled code
  res.setHeader('Content-Type', 'text/html; charset=utf-8')

Keywords: node.js Front-end Back-end

Added by tomcurcuruto on Sun, 30 Jan 2022 00:52:00 +0200