Today’s implementation is a simple list of articles, and then click to see the details, that’s all, but for use, it’s enough, blogging, making lists, and so on is very OK

Node modules involved:

const http = require('http');// Set up the server
const path = require('path');// Used to process paths
const fs = require('fs');// File reading module
const mime = require("./data/mime.json");// File suffix mapping table
const url = require('url');/ / processing the url
const cheerio = require('cheerio');// After the template is read, dom manipulation is convenient
Copy the code

In fact, I think a lot of front-end students learn Node’s purpose a little off track, as a scripting language, JS has a natural defect, although it can run in the server, but with Java, the big brother or not. Is there any need for Node to exist? Of course there is

Not all websites need a complex back end as a bottom support, just as I said before that not all websites have a good front end for a framework like Vue. Technology must be there to solve some problems, not all of them. So if you’re just doing a simple blogging system or something, you’ll have no problem using Node

Today, my case does not even need a database, which greatly reduces the cost of learning. It can be said that as long as the real front-end, then back-end code like this is really no pressure, not to say more, read on.

Write a random service and respond

The Node modules involved have been listed above, and their functions have also been commented, so it is not necessary to say more. Let’s take a look at the simplest server response to do:

const http = require('http');// Set up the server
const server = http.createServer((req,res) = >{
	res.end('hello gays~');
})
server.listen(8787);
Copy the code

Then run the js file in Node, and open it locally: http://localhost:8787/ to return ‘Hello Gays ~’.

How does Node run js files?

B: well… For example, if the code above is called index.js, open the command line, CD to this folder, and type Node index.js

If nodemon is used to run this file, you will need to run it again from the command line every time you modify it. If nodemon is used, you will refresh the page directly and install Nodemon globally. NPM install nodemon-g If you have a MAC address, you may need to add the sudo command before it: sudo NPM install nodemon-g

If nodemon index.js is running, the page will Say Hello to you.

Of course, just Say Hello, of course, is not enough We need to make the page, then it involves read the file, is our file on the server, enter the address is on the back end after the request, the back-end need to read the files in the server, and then returned to the client, and then displayed on the page, In Node, files are read using a built-in module: the FS module.

About FS module, I will write the article in detail, now we just need to know that we can use this module to read files and write files can, add, delete, change to check a little fault, but the efficiency can not be compared with the database, but for simple application, or that sentence, enough good.

For example, my current project structure is like this:

I’m now going to read SRC /news/index.html from the index.js entry in the project root directory

let resData = fs.readFileSync("./src/news/index.html");
console.log(resData);
// Get the result: 
      
// Convert the result
console.log(resData.toString());
// To get the correct HTML structure, return it to the client using res.end<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial =1.0"> <meta http-equiv=" x-UA-compatible "content=" IE =edge"> <title>title</title> </head> <body> <div class="newslist"></div> </body> </html>Copy the code

Normally, I would also need to render the data in the page

Just read the HTML file we don’t need to do back-end programs, directly read can be, so we also need to read the file for some modification, add data to it, this is actually a bit of SSR flavor. So there’s a new module involved: Cheerio.

This module allows us to manipulate the HTML files we read in the Node environment like JQ, so that the server-side data assembly process can be completed using the DOM manipulation that we are most familiar with on the front end.

NPM install Cheerio-s is the only non-built-in module used in this case: NPM install Cheerio-s

Throw the HTML that we read above with the FS module to cheerio, and we can do this

  let resData = fs.readFileSync("./src/news/index.html");
  let $ = cheerio.load(resData);
  $('.newslist').html('Structure after combining data');
  
  res.end($.html());// Finally, the content is thrown to the client
Copy the code

All the preparations… Wait, one more thing, normally, we need to introduce CSS in the page, this is also a request, how to handle?

Another module is needed: the PATH module

For example, we introduce CSS files in the page: ; So this time our node get request like this: http://localhost:8787/www/css/news.css

In general, the backend responds to requests from the front end by setting the response headerAt least this stuff has to be set, so the request in the page CSS, js, images, and so on all kinds of resources, to set? The request file suffixes can be extracted and compared with a table. Different suffixes are given different content-Types.

So mime. Json is born, and it’s a long thing,Click here toYou can see

Once we have it, we need to first introduce it into the project, and then make a judgment:

const mime = require("./data/mime.json");// File suffix mapping table
let extName = path.extname(req.url);

const server = http.createServer((req,res) = >{
  /* Handle other file requests and set the corresponding header file */ according to the different file formats
  if(extName && extName ! ='.ico'){
    res.setHeader("Content-Type", mime[extName]);
    let resData = fs.readFileSync("." + req.url);
    res.end(resData);
  }else{
    res.setHeader("Content-Type"."text/html; charset=utf-8"); }}); server.listen(8787);
Copy the code

I also made a safety net, because HTML can display most documents, so when the suffix is not read, it is set to HTML by default. In addition, sometimes we can enter the domain name and port, and then we can not get the suffix, so we can kill two birds with one bird.

With that in mind, we can start writing the project

The first step is to prepare static files such as HTML, CSS and IMG, and then use JSON to store the corresponding data

Directory structure now:

app   
  -data
    -data.json // Where to store data
  -node_modules / / rely on
  -src
    -detail
      -index.html // Here is the template
      -index.js  // Process the template
    -news
      -index.html  / / template
      -index.js  // Process the template
  -www // Static file
    -css
    -img
  index.js // Project entry
Copy the code

Step 2, write the entry file

const http = require('http');// Set up the server
const path = require('path');
const fs = require('fs');// File reading module
const mime = require("./data/mime.json");// File suffix mapping table
const url = require('url');/ / processing the url

const server = http.createServer((req,res) = >{

    let objPath = url.parse(req.url,true);
    let pathname = objPath.pathname;// Routing data
    let extName = path.extname(req.url);

    /* Handle other file requests and set the corresponding header file */ according to the different file formats
    if(extName && extName ! ='.ico'){
        res.setHeader("Content-Type", mime[extName]);
        let resData = fs.readFileSync("." + req.url);
        res.end(resData);
    }else{
        res.setHeader("Content-Type"."text/html; charset=utf-8");
    }

    Routing / * * /
    switch (pathname) {
        case '/':
        case '/news':
            const viewNewsData = require('./src/news/index');
            res.end(viewNewsData(objPath));
            break;
        case '/detail':
            const viewDetailData = require('./src/detail/index');
            res.end(viewDetailData(objPath));
            break;
        default:
            break; }}); server.listen(8787);
Copy the code

Third, separate the modules to handle the logic in the page

This is the news list processing module:

const fs = require('fs');// File reading module
const cheerio = require('cheerio');// After the template is read, dom manipulation is convenient
let newsData = require(".. /.. /data/data.json");

function viewNewsData(objPath){
    let indexData = fs.readFileSync('./src/news/index.html');// Read the content

    let query = objPath.query;/ / search information
    let nowPage = query.page || 1;/ / the current page
    let pageNum = 6;// The amount of data per page
    let pageCount = Math.ceil(newsData.length/pageNum);// Count the total number of pages

    let newsHtml = ' ';
    let paginationHtml = ' ';


    /* Process content data */
    let nData = JSON.parse(JSON.stringify(newsData)).splice((nowPage-1)*pageNum,pageNum);// Copy the data and then cut the data according to the page number;
    
    nData.forEach((item) = >{
        newsHtml +=` <li class="news"> <a href="/detail? id=${item.id}">
                <img src="${item.imgUrl}" alt="">
            
                <div class="content">
                    <h3 class="title">${item.title}</h3>
                    <div class="info">
                        <span class="tips"><span>${item.from}</span></span> <! -- <span class="line"></span> --> <span class="time">| &nbsp; &nbsp;${item.newTime}</span>
                    </div>
                </div>
            </a>
        </li>
    `;
    });
    /* Process content data */

    let $ = cheerio.load(indexData);
    $('.news-list').html(newsHtml);
    return $.html();
}


module.exports = viewNewsData;
Copy the code

OK, basically the whole project is finished. Later, you only need to edit the JSON file to update the content of the page. Is it still very simple? Hi will show you more Node modules in the future, so we can do more things.

All the resources in the article can be downloaded here


  • This is our open source project element3 from the Flower mountain team welcome to try and star
  • A front-end component library that supports VUE3