“This article is participating in the technical topic essay node.js advanced road, click to see details”

preface

The “go from” to “proficient” in Node.js is a Flag that has been around for a long time, and has been around since last year. Awakening of Insects has passed, the wind warm clouds open, the next year’s Flag is the time to take out to achieve. I decide to choose the latter.

At least the exploration of Node.js will have a perfect exclamation point this year.

Specific goals

Personally, I prefer to actually write features as I learn them, but I’m limited to Node, so I turn to articles by gold diggers, some of which are excellent for implementing specific features. So I started a happy learning journey. The reference article has been placed at the end of the article, the main reference is xu Xiaoxi, he has a lot of articles about node.js development projects, both the article content and programming thinking are very good.

The main purpose of this article is to record some of the gains FROM my study and the solutions to the problems I encountered.

Go with the flow of nowhere, ride the wind and waves to aid the sea

Little examples of joy

Email sending function

Function implementation

Using Nodemailer, 30 lines of code can be used to send mail. For the email sending function, you need to fill in the sender email address, sender email authorization code, sender email host address and port number, and recipient email address. If you want to add an attachment, enter the attachment name and attachment resource address.

'use strict';
const nodemailer = require('nodemailer');

// async.. await is not allowed in global scope, must use a wrapper
async function main() {
  let user = 'Actual sender's email address';
  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: 'smtp.qq.com'.port: 587.secure: false.// true for 465, false for other ports
    auth: {
      user: user, // generated ethereal user
      pass: 'Sender email Authorization Code'.// generated ethereal password}});return await transporter.sendMail({
    from: 'ye Yi 🐇' <${user}> `.// sender address
    to: '[email protected]'.// list of receivers
    subject: 'Hello World'.// Subject line
    text: 'Hello World'.// plain text body
    html: 'Hello : young man 
       '.// html body
    attachments: [{filename: 'First.doc'.path: 'https://xxx.doc'],},// Add Attachments to messages
  });
}

main().catch(console.error);
Copy the code

Recipient email Indicates the received email information

Among them

  • Sender email authorization code, check in the mail Settings, qq mailbox, for example, in the mail Settings – > account, POP3 / IMAP/SMTP/Exchange/CardDAV CalDAV services TAB, click the generate the authorization code, via text message after verification can get authorization code; You can also see the official documents provided by Tencent have a very detailed acquisition process.

  • The host address and port number of sender’s email. Take QQ email as an example, I found it in the help center. The host address is smtp.qq.com and the port number is 465 or 587

  • Attachments can be added to messages by setting attachments, and custom attachment names and attachment resource addresses are supported

summary

  • Nodemailer is an easy-to-use Node.js mail module (via SMTP, Sendmail, or Amazon SES) that supports Unicode and can use any character set you like. In the actual development, the customization is stronger, which I still need to explore in the future;
  • How to use NodeJS to automatically send mail? The meaning and usage of each field are detailed in this article, and the open source mail template is also listed at the end of the article, which is well worth a look.

I’ve heard so much about scheduled tasks

The node module node-schedule helps implement the scheduled task function. Many business scenarios require scheduled tasks, such as billing emails to users at the end of each month, running sales data every other day, and so on.

Node Schedule is a flexible Cron-like, cron-like job scheduler for Node.js. It allows you to schedule jobs (any function) to be executed on a specific date, with optional repetition rules. It uses only one timer at any given time (rather than reevaluating upcoming work per second/minute).

Interesting Cron style

I saw the format on Cron website, how come there are asterisks and numbers and letters? That’s interesting.

Looking at a detailed explanation of each location, it’s not hard to see that Cron provides fields that cover almost every point in time.

The field name permitted Special characters allowed
Seconds (Seconds) 0 ~ 59 , – * /
(Minutes) 0-59 , – * /
Hours 0-23 – * /
Day of Month 1-31 * /, -?
Month 1-12 or JAN-DEC – * /
Day of Week 0-6 or SUN-SAT * /, -?

Note: The month and day of the week field values are case insensitive. “SUN”, “SUN” and “SUN” are also accepted.

Cron expression

A Cron expression is a string separated by five or six Spaces and divided into six or seven fields, each field representing a meaning. Cron has the following two syntax formats:

Seconds Minutes Hours DayofMonth Month DayofWeek Year or Seconds Minutes Hours DayofMonth Month DayofWeekCopy the code

A scheduled task implemented using node-schedule

  • An email is sent at the tenth second of every minute, which we have already implemented;
  • After the email has been sent for three times, the scheduled task is cancelled.
  • Try more time Settings for scheduled tasks;
const schedule = require('node-schedule');
const sendEMail = require('./sendEmail');

/** * Scheduled task */
const creatSchedule = timePoint= > {
  let count = 1;
  const all = schedule.scheduleJob(timePoint, () = > {
    console.log('Send mail:' + new Date());
    // Send an email
    sendEMail.main();
    count++;
  });
  setTimeout(() = > {
    console.log('Cancel scheduled task :' + new Date());
    all.cancel();
  }, 180000);
};

let timePoint = '10 * * * * *';
creatSchedule(timePoint);
Copy the code

Print the result

In addition to using characters such as numbers and asterisks to set the time, Node-schedule also provides custom rules. You can set the time according to the custom rules in a more intuitive way.

  • New scheduler.RecurrenceRule instance timePoint;
  • The RecurrenceRule attributes include

second (0-59)

minute (0-59)

hour (0-23)

date (1-31)

month (0-11)

year

dayOfWeek (0-6) Starting with Sunday

tz

  • Mail is sent at the 11th second of every minute, otherwise the same as above;
const schedule = require('node-schedule');
const sendEMail = require('./sendEmail');

/** * Scheduled task */
const creatSchedule = timePoint= > {
  let count = 1;
  const all = schedule.scheduleJob(timePoint, () = > {
    console.log('Send mail:' + new Date());
    // Send an email
    sendEMail.main();
    count++;
  });
  setTimeout(() = > {
    console.log('Cancel scheduled task :' + new Date());
    all.cancel();
  }, 180000);
};
let timePoint = new schedule.RecurrenceRule();
timePoint.second = 11;
creatSchedule(timePoint);
Copy the code

Print the result

summary

  • Mastered the basic new scheduled task;
  • Cancelling scheduled tasks was also attempted;
  • The actual business situation is a little more complicated and more fun to explore
  • The explanation on the official website is more detailed. If you have any questions, you can check the official website

File copy

Learning Node.js is not necessarily about learning modules, but Node.js provides a large number of modules, and how to use them in a project is obviously a measure of how well you have mastered Node.

If you want to do file manipulation in our project, the FS module needs to be mastered.

Fs module has a large number of API, detailed introduction can refer to the official website. Here I mainly try the file copy function.

Buffer for the first time

The JavaScript language itself only has string data types, not binary data types. But when dealing with things like TCP streams or file streams, you must use binary data. Therefore, in Node.js, a Buffer class is defined to create a Buffer dedicated to binary data.

  • A Buffer object is used to represent a fixed-length sequence of bytes. Many Node.js apis support buffers.
  • The Buffer class is a subclass of the JavaScript Uint8Array class and extends it with methods that cover additional use cases. The Node.js API also accepts the ordinary Uint8Array where buffers are supported.
  • Although the Buffer class is available in global scope, it is still recommended to refer to it explicitly through import or require statements.
const buffer = require('buffer');

// Create a zero-filled buffer of length 10.
const buf1 = buffer.Buffer.alloc(10);

// Create a buffer of length 10,
// Populate with bytes of value '1'.
const buf2 = buffer.Buffer.alloc(10.1);
Copy the code

Multiple reads implement file copy

  • Buffer Creates a buffer that is read and written to each time.
  • Fs. open Asynchronously opens the file to be operated on;
  • Fs. read Reads the source file;
  • Fs. write Writes to the target file;
  • When there is no data to read, close the source file and the target file and synchronize the buffer.
  • Note that the next method is called in a loop, so when there is no data to read, we need to abort the next method by returning.
const fs = require('fs');
const buffer = require('buffer');

/** * multiple reads implement file copy *@param {string} InitFile Source file path *@param {string} CopyFile Target file path *@param {number} BufSize Buffer size */
function copyFunc(initFile, copyFile, bufSize) {
  // Open the source file
  fs.open(initFile, 'r'.(err, readFd) = > {
    // Open the target file
    fs.open(copyFile, 'w'.(err, writeFd) = > {
      let buf = buffer.Buffer.alloc(bufSize); // Create an empty buffer with the value of size
      let readFlag = 0; // The location of the source file to read next
      let writeFlag = 0; // The location of the target file to be written next time

      (function next() {
        // Read the source file
        fs.read(readFd, buf, 0, bufSize, readFlag, (err, bytesRead) = > {
          readFlag += bytesRead;

          // Close the source file if it has no replicable content
          if(! bytesRead) fs.close(readFd,err= > console.log('Copy completed, close source file'));

          // Write to the target file
          fs.write(writeFd, buf, 0, bytesRead, writeFlag, (err, bytesWritten) = > {
            // Close the target file if the source file does not have a copiable content synchronization buffer
            if(! bytesWritten) { fs.fsync(writeFd,err= > {
                console.log('Copy done, sync cache');
                fs.close(writeFd, err= > {
                  console.log('Copy completed, close target file');
                });
              });
              return; // Close execution of the next function
            }
            writeFlag += bytesWritten;
            // Continue reading and writingnext(); }); }); }) (); }); }); }// The length of the buffer
const bufSize = 20;
copyFunc('./files/init.txt'.'./files/copy.txt', bufSize);
Copy the code

summary

  • This is a bonus for knowing about buffer.
  • Through the actual function realization, deepen fs about read and write API cognition;
  • File I/O is relatively basic knowledge content, quite rare in the front-end daily development, this simple implementation of a small function, is a small step forward.

conclusion

When learning a new technology, if you find that you cannot achieve the actual function development through document learning, it is suggested to do some small function auxiliary exercises and apply the knowledge points learned after learning.

Kang Su asked, “Do you also know how to shoot? Isn’t my shooting also fine?” Weng said, “There is no other, but his hand is familiar.” Kang Su angrily said: “You dare light I shoot!” Weng said, “I know it by drinking oil.” He took a gourd and put it on the ground, covered its mouth with money, and dripped oil from the money hole, but the money was not wet. He said, “I have no one but my hand.

Refer to the article

  • How do I use NodeJS to automatically send mail?
  • Node.js advanced fs file module learning
  • 13+ FaQs and solutions encountered in the Recovery Node project