Node basic knowledge sorting

1.fs module

EsmaScript is used for coding in node, without Bom and Dom, which is different from JS in browser.
js in the browser does not have the ability to operate files, but js in Node can operate files.
fs is short for file system, which is the word system. To use this core module in the Node, you need to introduce.

1. Read files

Node is an error first callback function
The first parameter returns an error and verifies whether it has an error; Other parameters return data.
The first parameter is the file path to be read. The second parameter is the encoding type. Generally, you can fill in utf-8 directly. Otherwise, the read file is garbled. The third parameter is a callback function.

2. Writing documents

The first parameter is the file path to be read, the second is the content written, and the third parameter is a callback function.

fs.writeFile('red2.txt', 'Hello everyone, I'm xxx!', (err) => {
    if (err) {
        console.log('Error you file');
    } else {

3. Encapsulation

1. Direct packaging

const fileMethod= {
    readFile: (path, cb) => {
        fs.readFile(path, 'utf8', (err, data) => {
            if (!err) {
    writeFile: (path, content, cb) => {
        fs.writeFile(path, content, 'utf8', (err) => {
            if (!err) {
var pathUrl = './modb/studen.json'
//readFile call
 fileMethod.readFile(pathUrl, (data) => {})
//WriteFile call
 fileMethod.writeFile(pathUrl, JSON.stringify(DataObj), () => {
     console.log('Write successful')

2.promise package

//pathUrl is the path
function readFiles(pathUrl) {
    return new Promise((resolve) => {
        fs.readFile(pathUrl, 'utf-8', (err, data) => {
            if (!err) resolve(data)
//pathUrl is the path and attr is the saved information
function writeFiles(pathUrl, attr) {
    return new Promise((resolve) => {
        fs.writeFile(pathUrl, attr, 'utf-8', (err, data) => {
            if (!err) resolve(data)

//readFile call
var pathUrl = './modb/studen.json'
readFiles(pathUrl).then((res) => {

  writeFiles(pathUrl, 'helloWorld22').then((res) => {

2.http create simple server

Node specifically provides a core module http, which can be used to create a web server.
response.write can be used multiple times, but end must be used to end the response, otherwise it will wait all the time.

var http = require('http'); //1 load HTTP module
var serve = http.createServer(); //2. Create a serve instance
//3 initiate request
serve.on('request', (request, response) => {
    response.write('Seccess Server')
// 4 start the server
serve.listen(3000, function () {
    console.log('Server started successfully!,visit, view ');

Start command:

node  https.js

Return different data according to different request paths

response.end(); It can pass string or Buffer type

serve.on('request', (request, response) => {
    console.log('Output received server request address', request.url);
    if (request.url.includes('Login')) {
        response.write('Is Login');
    } else if (request.url.includes('zhuce')) {
        response.write('Is register');
    } else {
        response.write('404 Not Found');

Concept of Ip and port number

Ip location computer

console.log('Get address', req.socket.remoteAddress);

Port number location application

console.log('Get port', req.socket.remotePort);

The computer has some default port numbers. Don't use them at last.
In the development, use some simple ones, such as 3000500080·····

Set utf-8 coding to solve garbled code


The response content type (request header) needs to be set

res.setHeader('content-type', 'application/json; charset=utf-8');

· Content-Type Content type sends the data type data in the file
 Common media format types are as follows:
text/html :  HTML format
text/plain : Plain text format
text/xml :  XML format
image/gif : gif Picture format
image/jpeg : jpg Picture format
image/png: png Picture format
· with application Media format type starting with:
application/xhtml+xml : XHTML format
application/xml:  XML data format
application/atom+xml : Atom XML Aggregate format
application/json:  JSON data format
application/pdf: pdf format
application/msword :  Word Document format
application/octet-stream :  Binary stream data (such as common file downloads)
application/x-www-form-urlencoded :  <form encType="">Default in encType,form The form data is encoded as key/value Send format to the server (the default format for submitting data in the form)

Server chaining

var http = require('http');
http.createServer((req, res) => {
}).listen(80, () => {
    console.log('serve is success.please visit location adress');

Template syntax

1. Installation

npm install art-template --save
  1. Introducing in node
var templates = require('art-template');

3. Read

    fs.readFile('./assest/index.html', (err, data) => {
            if (err) {
                res.end('is 404');
            var htmlStr = templates.render(data.toString(), {
                msg: 'This is a piece of data'

4. Output in html page

<!DOCTYPE html>
<html lang="en">
        <meta charset="UTF-8" />

        <h1>node read index success</h1>
       {{each msg}}
        <div class="box">
            <h1>{{$}} : </h1>


3.url template

Use require to import directly in node.

var url = require('url');

The methods in Url are as follows:

        Url: [Function: Url],
        parse: [Function: urlParse],
        resolve: [Function: urlResolve],
        resolveObject: [Function: urlResolveObject],
        format: [Function: urlFormat],
        URL: [class URL],
        URLSearchParams: [class URLSearchParams],
        domainToASCII: [Function: domainToASCII],
        domainToUnicode: [Function: domainToUnicode],
        pathToFileURL: [Function: pathToFileURL],
        fileURLToPath: [Function: fileURLToPath]

The pathname path and query parameters can be obtained through the parse method

url.parse(req.url, true);
Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?a=1&b=2',
  query: 'a=1&b=2',
  pathname: '/getmsg',
  path: '/getmsg?a=1&b=2',
  href: '/getmsg?a=1&b=2'

Convert json data into string format through JSON.stringify() and display it on the page.

if (pathName === '/sendMsg') {

4. Introduction and throwing of documents


Import the file with require and throw it with exports in another js file.
Note: exports can only be thrown individually.

var b = require('./b');


var str = 'This is b str';
var str_no2 = 'This is b str_no2';
exports.str = str;
exports.str_no2 = str_no2;

Output returns an object


Use require to import the file, and use module.exports to throw in another js file.
Note: multiple modules. Exports can be thrown together.

var b = require('./b');


var str = 'This is b str';
var str2 = 'This is b str2';
module.exports = { str, str2 };

5.Express framework

Native http is not enough to meet our development needs in some aspects, so we need to use the framework to speed up our development efficiency. The purpose of the framework is to improve efficiency and make our code more unified.


Enter npm init -y in the file (this can skip the wizard and directly produce). A package.json file will be added to the document to store the downloaded and installed packages.
Then open the command prompt block input

npm intsall express --save

Download framework

Basic use

Directly introduce express, and you only need to add get/post after sending the request.

var express = require('express');
var app = express();

app.get('/', (req, res) => {
    res.send('hello express');

app.get('/getMsg', (req, res) => {
    arr = [
        { name: 'ha-ha', age: 18 },
        { name: 'Hee hee', age: 20 }

app.listen(3000, () => {

Details of request and response objects:

Request object - the request object represents an HTTP request, including the request query string, parameters, content, HTTP header and other attributes. Common attributes are: when the callback is an external file, use to access the instance of express
2.req.baseUrl: get the URL path of the current installation of the route
3.req.body / req.cookies: obtain "request subject" / Cookies
4.req.fresh / req.stale: judge whether the request is still "fresh"
5.req.hostname / req.ip: obtain the host name and IP address
6.req.originalUrl: get the original request URL
7. Req. Parameters: get the parameters of the route
8.req.path: get request path
9.req.protocol: get protocol type
10.req.query: get the query parameter string of the URL
11.req.route: get the current matching route
12.req.subdomains: get subdomain name
13.req.accepts(): check the document type of the acceptable request
14.req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages: returns the first acceptable character encoding of the specified character set
15.req.get(): get the specified HTTP request header determine the MIME type of the content type of the request header

Response object - the response object represents the HTTP response, that is, the HTTP response data sent to the client when the request is received. Common attributes are: same as
2.res.append(): append the specified HTTP header
3.res.set() resets the previously set header after res.append()
4.res.cookie(name, value [, option]): set the Cookie
5.opition: domain / expires / httpOnly / maxAge / path / secure / signed
6.res.clearCookie(): clear cookies transfer the files in the specified path
8.res.get(): returns the specified HTTP header
9.res.json(): transfer JSON response
10.res.jsonp(): send JSONP response
11.res.location(): only set the Location HTTP header of the response, not the status code or close response
12.res.redirect(): set the Location HTTP header of the response and the status code 302
13. Res.render (view, [locales], callback): render a view and pass the rendered string to callback. If an error occurs during rendering, next(err) will be called automatically. The callback will be passed in a possible error and the rendered page, so it will not be output automatically.
14.res.send(): send HTTP response
15.res.sendFile(path [, options] [, fn]): transfer the file with the specified path - the content type will be automatically set according to the file extension
16.res.set(): set HTTP headers. Multiple headers can be set for incoming object s at one time
17.res.status(): sets the HTTP status code
18.res.type(): sets the MIME type of content type

Hosting static files with Express

Express provides a built-in middleware express.static to set static files, such as pictures, CSS, JavaScript, etc.
You can use the express.static middleware to set the static file path. For example, if you put pictures, CSS and JavaScript files in the public directory, you can write:
1. Import static file directory


2. The directory structure is shown in the figure below

3. Enter in the browser to access

Automatically restart the server after modifying the code

nodemon is a third-party naming tool developed based on Node, which can solve the problem of frequently modifying code and restarting the server
Download method (directly install in the global):

npm install --golbal nodemon  
npm i -g nodemon 

After installation:

nodemon app.js

Verify successful installation:

nodemon --version  
nodemon -v

Redirection problem

The original framework redirection is not used. It needs to be written as follows:

res.statusCode = 302;
res.setHeader('Location', '/');

Now you can use the express framework in one step:


Get/post request get parameters

1.get request to obtain parameters

app.get('/get, (req, res) => {
}); request to obtain parameters

Express has no built-in api for obtaining post request parameters. You need to download a package: bode parser


npm install --save body-parser

Introduce and configure in app.js

var bodyParser = require('body-parser')
//Configure the body parser plug-in (resolve post request parameters)
app.use(bodyParser.urlencoded({ extended: false }))
//Then you can call body under req.'/getPost', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*') //Cross domain

The printout can be viewed, which contains the transmitted parameters

6. Basic usage of express template syntax

Download plug-ins

npm install --save express-art-template

File directory
The pages are uniformly placed under the views folder, and one is built without.
views is the default directory for the page.

Modify directory path

app.set("view",File path)

Introducing plug-ins

const express = require('express');
const app = express();
app.engine('html', require('express-art-template'));
const port = 80;
app.get('/', (req, res) => {
    res.render('404.html', {
        title: 'The page you visited has been lost 404~'
app.listen(port, () => console.log(``));

Use in page

<!DOCTYPE html>
<html lang="en">
        <meta charset="UTF-8" />

Tags: node.js

Posted on Mon, 18 Oct 2021 22:19:41 -0400 by MikeUK