Detailed explanation of how to use Node.js to implement hot reload page

Detailed explanation of how to use Node.js to implement hot reload page

Preface

Not long ago, I combined browser-sync+gulp+gulp-nodemon to implement a project scaffolding for hot updates in the production environment (my previous understanding was a bit biased, it should be defined as hot updates, not hot reloads). So, today we will use Node.js to implement a hot reload page.

Well, let me summarize today to prevent you from making the same mistake as me.

Hot Reload

The so-called hot reload means that every time the page is changed, it can be refreshed automatically without manual refresh.

Hot Update

The browser's refresh-free update allows various modules to be replaced, added, or removed at runtime without having to perform a full refresh to reload the entire page.

Purpose: To speed up development, so it is only suitable for use in a development environment.

Idea: Preserve the state of the application that is lost when fully reloading the page, and only update the changed content to save development time. Adjusting styles is faster and almost equivalent to changing styles in the browser debugger.

Actual Combat

1. Initialize the project

Here, use the following command to initialize the project. I use the -y suffix here for faster and more convenient initialization. If you want to customize it, you can type it line by line.

npm init -y

Initialization is complete, and there is an additional package.json file in the root directory.

2. Create the Node main file app.js

Next, we will create a Nodejs operation main file app.js.

const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
const path = require('path');
const fs = require('fs');
const io = require('socket.io')(server);

app.use(express.static(path.join(__dirname, './public')));
createWatcher();

function createWatcher() {
  const absolute = './public';
  fs.watch(absolute, function (eventType, filename) {
    if (filename) {
      io.sockets.emit('reload');
    }
  });
}

server.listen(8086, function () {
  console.log(`The server is running on port 8086.`);
});

First, we create an http server using a combination of http and express, and bind it to socket.io. Then we use express to host static files and specify the static file directory public. Here we use the watch method under the fs module to monitor changes in the file directory. If the files in the directory are changed, the line io.sockets.emit('reload'); will be triggered. Now that it has been triggered, there must be a place to monitor it.

3. Create index.html file

We will create a public folder in the root directory and an index.html file in the folder.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Hot Update Page</title>
    <link rel="stylesheet" href="style.css" rel="external nofollow" />
    <style>
      h1 {
        color: red;
      }
    </style>
  </head>
  <body>
    <h1>Hello</h1>
    <p class="txt">Text</p>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
    </ul>
    <p class="name"></p>
    <script src="./socket.io.min.js"></script>
    <script src="./index.js" type="module"></script>
    <script type="module">
      import obj from './index.js';
      io.connect('http://localhost:8086/').on('reload', () =>
        window.location.reload()
      );
      document.querySelector('.name').innerHTML = obj.name;
    </script>
  </body>
</html>

The file content is as above. The first thing we need to pay attention to is how to monitor with the background. We only need to import the socket.io.min.js file (I will give the source code address at the end of the article), and then type the following code below:

io.connect('http://localhost:8086/').on('reload', () =>window.location.reload());

http://localhost:8086/ This is the address of the backend. You need to listen to this address to communicate with the backend. Because we customized a reload event in the background, the front-end only needs to listen to this event. If this event is triggered in the background, the foreground will listen to it and execute code randomly.

4. Create other types of files

We can see in the index.html file above that I have externally imported the index.js file and the style.js file. The main purpose is to detect whether the page will change accordingly if the code is changed. The answer is yes.

5. Real-time update page

We start by launching the project.

node app.js

You will see that the terminal will display The server is running on port 8086. Then you can open the address http://localhost:8086/ in the browser. When we change the code, we can see the page is displayed in real time, and when we press the shortcut key to save the code (it is recommended that the editor does not automatically save the code in real time), the page is updated in real time.

Isn't this very convenient? You don't have to click refresh every time you switch pages. Thinking back to when I first used JQ to write pages, I felt so stupid for repeating the same work every time.

Conclusion

Thanks for reading, I hope I didn't waste your time.

Source code address: https://gitee.com/maomincoding/hot-load

This is the end of this article on how to use Node.js to implement hot reload pages. For more relevant Node.js hot reload page content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example code for implementing hot update of Typescript project with nodemon
  • Detailed explanation of webpack2+node+react+babel to achieve hot loading (hmr)
  • Webpack implements Node.js code hot replacement
  • Node.js cleverly implements hot update of Web application code

<<:  Example of using mycat to implement MySQL database read-write separation

>>:  How to install pip package in Linux

Recommend

How to optimize the slow Like fuzzy query in MySQL

Table of contents 1. Introduction: 2. The first i...

How to implement on-demand import and global import in element-plus

Table of contents Import on demand: Global Import...

Summary of HTML Hack Tags in IE Browser

Copy code The code is as follows: <!--[if !IE]...

What are the advantages of using B+Tree as an index in MySQL?

Table of contents Why do databases need indexes? ...

5 ways to migrate Docker containers to other servers

Migration is unavoidable in many cases. Hardware ...

Summary of the advantages of Vue3 vs. Vue2

Table of contents 1. Why do we need vue3? 2. Adva...

How to use CURRENT_TIMESTAMP in MySQL

Table of contents Use of CURRENT_TIMESTAMP timest...

Detailed explanation of Nginx passively checking the server's survival status

introduce Monitors the health of HTTP servers in ...

How to create LVM for XFS file system in Ubuntu

Preface lvm (Logical Volume Manager) logical volu...

An article teaches you how to use js to achieve the barrage effect

Table of contents Create a new html file: Create ...

Two ways to open and close the mysql service

Method 1: Use cmd command First, open our DOS win...

Vue implements login type switching

This article example shares the specific code of ...

Nginx reverse proxy to go-fastdfs case explanation

background go-fastdfs is a distributed file syste...

Automatic file synchronization between two Linux servers

When server B (172.17.166.11) is powered on or re...

How to use vuex in Vue project

Table of contents What is Vuex? Vuex usage cycle ...