This article mainly introduces the process of learning NodeJS, the realization of server code update client automatic refresh function, improve the learning efficiency process

Background:

When learning Node, you always need to run manually. When writing restful apis, you need to refresh the browser manually. The process is lengthy, and the interest in learning NodeJS is directly halved.

Goal:

  1. Step1 realizes the automatic run after nodeJS is saved instead of the manual run every time
  2. Step2 when writing restful services, the browser page automatically refreshes

Step1: Implement the automatic run after nodeJS is saved instead of the manual run every time

In./script.js, listen for index.js changes and create a child process to solve the problem of manual run

// ./script.js
const fs = require('fs')
const childProcess = require('child_process')
console.log('execution script');
let child = childProcess.fork(__dirname,['/index.js']);
fs.watch(__dirname + '/index.js'.function(err, data) {
    console.log(err, data);
    console.log('Changed');
    child.kill('SIGHUP')
    child = childProcess.fork(__dirname,['/index.js']);
})
Copy the code

Start the node service node script.js

Create the server service using http.createserver in./index.js

// ./index.js
const server = http.createServer(function (req, res) {
    if (url.parse(req.url).pathname === '/favicon.ico') return;
    // TODO
})
Copy the code

Step2: Implement restful services on the basis of setP1, and the browser page automatically refreshes

After the server restarts, the client can automatically refresh. For example, window.reload() uses a full-duplex socket service, which can be interpreted as the server can actively send messages to the client. Start by creating an HTML file to use as the client.

<! -- ./index.html -->
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/socket.io.min.js"></script>
<body>Restful services</body>
<script>
   // Send a request to the user with the given ID
axios.get('http://127.0.0.1:3003/userList')
    .then(function (response) {
    // Handle the success
    console.log(response);
    })
    .catch(function (error) {
    // Handle error conditions
    console.log(error);
    })
    .then(function () {
    // Always execute
    });
    console.log(axios);
    const socket = io('ws: / / 127.0.0.1:3002', {path: '/sockettest'.withCredentials: true.extraHeaders: {
            "my-custom-header": "abcd"}});console.log(socket);
</script>
</html>
Copy the code

On the client side, the modules Axios and socket. IO are introduced directly


Add another socket service to./index.js on the server

// ./index.js
const wsserver = require('http').createServer();
const io = require('socket.io')(wsserver, {
    path: '/sockettest'.pingInterval: 10000.pingTimeout: 5000.cors: {
      origin: "http://127.0.0.1:8080".methods: ["GET"."POST"].allowedHeaders: ["my-custom-header"].credentials: true}}); wsserver.listen(3002);
console.log('the socket port 3002');
Copy the code

Now nodescript.js starts two services (restful service and socket service) and double-click to open the HTML file. Page error across domains. Open HTML directly, is the file file service file://, does not have the TCP protocol, the same does not have cross-domain capability, in plain English, is lost the ability to communicate with the outside world. That requires putting the HTML in a service to use.


At this point, do you want to start a Node service for HTML presentation? Try Nginx.

This is the end of the article, with screenshots

Changes to./index.js now trigger a restart of the service (node, socket), and the client automatically requests the interface

conclusion

- In this article, not many plugins and frameworks are used, such as KOA Express Vue, etc., just axios socket; - The goal is also to simplify learning NodeJS; - two services are written in index.js, and each change is to stop and start the two services, slightly rude; - Socket service has its own heartbeat function, actually instead of our manual rotation; - If you have more than one API to test later, you can introduce the observer mode and re-request only one API that has changed.Copy the code