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

Linux loading vmlinux debugging

Loading kernel symbols using gdb arm-eabi-gdb out...

The process of installing SVN on Ubuntu 16.04.5LTS

This article briefly introduces the process of se...

MySQL 5.7.18 free installation version configuration tutorial

MySQL 5.7.18 free installation version installati...

HTML image img tag_Powernode Java Academy

summary Project description format <img src=&q...

Win2008 Server Security Check Steps Guide (Daily Maintenance Instructions)

The document has been written for a while, but I ...

Summary and practice of javascript prototype chain diagram

Table of contents Prototype chain We can implemen...

Example of how to quickly build a Redis cluster with Docker

What is Redis Cluster Redis cluster is a distribu...

Detailed explanation of encoding issues during MySQL command line operations

1. Check the MySQL database encoding mysql -u use...

CSS scroll-snap scroll event stop and element position detection implementation

1. Scroll Snap is a must-have skill for front-end...

js to achieve star flash effects

This article example shares the specific code of ...

Comparative Analysis of High Availability Solutions of Oracle and MySQL

Regarding the high availability solutions for Ora...

JavaScript to implement the web version of the snake game

This article shares the specific code for JavaScr...

Three Ways to Lock and Unlock User Accounts in Linux

If you already have some kind of password policy ...

Example of integrating Kafka with Nginx

background nginx-kafka-module is a plug-in for ng...