Nodejs plug-in and usage summary

Nodejs plug-in and usage summary

The operating environment of this tutorial: Windows 7 system, nodejs version 12.19.0, DELL G3 computer.

Nodejs plugin

1. Node-xlsx reads and writes Excel

Importing and exporting Excel files is a common problem in many systems, and NodeJS is no exception. Now, we will use NodeJS to read and write Excel files.

In NodeJS, we use a third-party tool called node-xlsx to read and write files. This module supports both the 2003 Excel (.xls) format and the 2007 Excel (.xlsx) format.

Now, let's take a look at the specific operation of this module

Reading operations on Excel

First, we need to install this module

cnpm install node-xlsx --save

The second step is to import the module and read the Excel file

const xlsx=require('node-xlsx');const DBUtil=require('./utils/DBUtil.js');const fs=require('fs');const path=require('path');function readExcel(path){
  var excel=xlsx.parse(path);
  return excel;}var obj=readExcel(path.join(__dirname,"./files/studentinfo.xls"));console.log(obj[0].data);

The above code has completed the reading operation of the Excel file. At this time, we read out an object and can see the information in it in the console

Writing to Excel

Now, we will demonstrate how to read the information of a table in the database and save it to the local computer. The code is as follows

const excel=require('node-xlsx');const fs=require('fs');const path=require('path');const DBUtil=require('./utils/DBUtil.js');function writeExcel(){
  var conn=DBUtil.getConn();
  conn.query("select * from studentinfo",[],(err,result)=>{
    if(err){
 
    }
    else{
      var excelArr = [];
      var headerRow=[];
      for(var i in result[0]){
        headerRow.push(i);
      }
      excelArr.push(headerRow);
      for(var i=0;i<result.length;i++){
        var temp=[];
        for(var j=0;j<headerRow.length;j++){
          temp.push(result[i][headerRow[j]]);
        }
        excelArr.push(temp);
      }
      try {
        var buff=excel.build([{name:'student information',data:excelArr}]);
        fs.writeFileSync(path.join(__dirname,"./files/01.xlsx"),buff);
        console.log("ok");
      } catch (error) {
        console.log(err);
      }
    }
  });
  conn.end();}writeExcel();

Here, we find that writing to Excel is a little troublesome, because here, we need to recombine the results obtained in the database and then generate Excel

Think about it: If in the Express framework, the generated Excel file is allowed to be downloaded and saved locally by the user as follows?

2. Nodemailer sends emails

Nodejs has many usage scenarios for sending emails to users. For example, we often see that after a user registers, a registration message will be sent to the user's registered mailbox. At this time, if we want to complete this function, we need to use a third-party module of nodemailer. The specific usage steps are as follows:

Install the corresponding module

$ cnpm install nodemailer --asve
$ yarn add nodemailer

Import the module and complete the code

const nodemailer = require('nodemailer'); var transport = nodemailer.createTransport({
  service:"qq",
  auth:
    user:"[email protected]",
    pass:"peshapwpokgvcahe"
  }});var options={
  from:"[email protected]",
  to:"[email protected]",
  subject: "This is an email message sent from nodemailer",
  text: "This is an email message sent from nodemailer" + (new Date()).toLocaleString(),
  html:"<h2>This is a test email from <u>nodemail</u>...</h2>"}; transport.sendMail(options,(err,info)=>{
  if(err){
    console.log(err);
  }
  else{
    console.log(info);
  }});

Message after successful sending

{ accepted: [ '[email protected]' ],
  rejected: [],
  envelopeTime: 221,
  messageTime: 830,
  messageSize: 801,
  response: '250 Ok: queued as ',
  envelope: { from: '[email protected]', to: [ '[email protected]' ] },
  messageId: '<[email protected]>' }

At this time, as long as the program can complete our sending request at this place, it will return the above information. If you do not see the above information, we need to check the error returned here.

Note: When configuring the sending server, we can use a third-party server or a built-in server.

Thinking: If the content sent is replaced with a template

const fs = require('fs'); const path = require('path'); class MailTemplateModel {
  constructor(userName,u_id,registerTime,mail){
    this.userName=userName;
    this.u_id=u_id;
    this.registerTime=registerTime;
    this.mail=mail;
  }
  toString(){
    var str = `Dear ${this.userName} Hello!
    Welcome to register as our member. Your account is ${this.u_id} and your registration time is: ${this.registerTime}.
    Please keep your account and password safe. If you have any questions, please send an email to ${this.mail}!
    Thanks! I wish you a happy life! `;
    return str;
  }}module.exports=MailTemplateModel;

The above code encapsulates the content of the email to be sent into an object, and then uses template syntax to concatenate strings.

Think about it: We write the content of the email sent in a separate external txt file, and then implement it through the replace of the String object. How to implement this function?

3. child_process

Can create a subprocess and execute shell scripts.

4. Node-readability

A plugin that can convert website content into simple content.

5. connect

In fact, express also uses this plug-in, and you can also write web programs using connect.

6. express-session

This is a session plugin. The default is forever, which is different from tomcat's 30 minutes, so you need to set the timeout yourself.

7. basic-auth plugin

Used for the simplest authentication method, generally used in API requests.

8. bcryptjs plug-in (always reports an error during bcrypt installation)

Used to perform hash processing using salt.

9. Reptiles Collection:

(1) Crawling static pages and API data: request+cheerio/jsdom. Request is a request library that can request post and get information. After obtaining HTML data, it can be parsed using a third-party parsing library, such as cheerio. For js dynamic rendering pages, you can consider using jsdom, but unfortunately, this is synchronous and is not a browser after all.

(2) Crawling dynamically rendered pages

puppeteer: uses the Chromium browser, asynchronous requests, high efficiency, and opens many browser operation APIs, which is very convenient.

nightmare: The API is very easy to use, using the browser in electron. Although I have not used it, I feel that it is not as flexible as puppeteer.

jsdom:sync has made me give up using it. Same as selenium.

10. moment.js

This is a lightweight format parsing library. If you write a format parsing function yourself, you will need several dozen lines of function code. This is very convenient.

This is the end of this article about nodejs plug-ins and their usage. For more information about nodejs plug-ins, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

<<:  Detailed explanation of the box model size depends on its padding, margin, and border values

>>:  Detailed explanation of the difference between IE8 compatibility view (IE7 mode) and standalone IE7

Recommend

About debugging CSS cross-browser style bugs

The first thing to do is to pick a good browser. ...

Docker's four network types principle examples

Four network types: None: Do not configure any ne...

How to query the latest transaction ID in MySQL

Written in front: Sometimes you may need to view ...

JavaScript Canvas draws dynamic wireframe effect

This article shares the specific code of JavaScri...

Web page printing thin line table + page printing ultimate strategy

When I was printing for a client recently, he aske...

uni-app implements NFC reading function

This article shares the specific code of uni-app ...

A brief discussion on the application of Html web page table structured markup

Before talking about the structural markup of web...

mysql5.7.22 download process diagram

1. Go to the official website www.mysql.com and s...

Detailed explanation of uniapp painless token refresh method

When the front-end requests the interface, it is ...

Detailed explanation of JavaScript function this pointing problem

Table of contents 1. The direction of this in the...

Simple example of HTML text formatting (detailed explanation)

1. Text formatting: This example demonstrates how...