Encapsulating the Promise version of readFile

Write in front

We all know that there are two types of file reading

fs.readFileSync(); / / read synchronously
 fs.readFile(); / / asynchronous read
 Copy code

Promise is a solution of asynchronous programming. Can we encapsulate a promise version of readFile?

Intron

Let's take a look at teacher Ruan Yifeng's explanation that javascript is a single thread

Link: www.ruanyifeng.com/blog/2014/1...

One of the major characteristics of JavaScript language is single thread, that is to say, only one thing can be done at the same time. When a call is issued, it must wait for the last task to complete before the next task can be executed. This execution mode is called synchronization. Single thread means that all tasks need to be queued, and the last task will be executed only when the previous one is finished. If the previous task takes a long time, the latter has to wait all the time. The designer of JavaScript realized that at this time, the main thread can suspend the waiting tasks regardless of the IO device, and run the tasks in the later row first. Wait until the IO device returns the result, and then turn around to continue the pending task. Therefore, all tasks can be divided into two types: synchronous task and asynchronous task.

What is synchronous programming?

The so-called synchronous programming is that the computer executes the code line by line in order. The time-consuming execution of the current code task will block the subsequent code execution.

What is asynchronous programming?

The so-called asynchronous programming is that after the call is sent, the call returns directly. The caller will not get the result immediately, but will not block, and can continue to perform subsequent operations. In a word

The program does not need to be executed from top to bottom in code order

Required documents

This is the template.html file we are going to introduce

<html>
    <head></head>
    <link rel="stylesheet" href="style.css">
    <body>
        <h1>Don't eat Suara~</h1>
        <img src="./eat.jpg" alt="" width="100px" height="100px">
        <script src="./common.js"></script>
    </body>
</html>
Copy code

Styles and js can be written by myself. What I write is a bit rough. The preview effect on the local is as follows:

Read in synchronous mode

Now let's read this file synchronously

const Koa = require('koa'); 
const app = new Koa(); 
const static = require('koa-static');
const fs = require('fs');
const main = ctx => {
    ctx.response.type = 'html'; // Response header
    const html = fs.readFileSync('./template.html','utf-8');    // Synchronous read
    // console.log(html);
    ctx.response.body =html;
}
app.use(static('./'));
app.use(main); 
app.listen(3000);
Copy code

This is a synchronous write, which can cause blocking. For high concurrency, it is very time consuming.

Read asynchronously

Now let's use asynchronous methods with higher performance, faster speed and no blocking. The code is as follows:

const Koa = require('koa'); 
const app = new Koa(); 
const static = require('koa-static');
const fs = require('fs');
const main = async ctx => {
    ctx.response.type = 'html'; // Response header
    // Encapsulating the Promise version of readFile
    let pReadFile = function (filePath) {
        return new Promise(function (resolve, reject) {
            fs.readFile(filePath, 'utf-8', function (err, data) {
                if (err) {
                    reject(err);
                }
                resolve(data);
            });
        })
    }
    await pReadFile('./template.html').then(data => {
        ctx.response.body = data;
    })
}
app.use(static('./'));
app.use(main); // A service is enabled for Visitors to use
app.listen(3000);
Copy code

Preview effect

As you can see, we have successfully completed the encapsulation of Promise version in readFile.

Some explanations for the above codes

  • Koa static is introduced to deal with static resources
  • Promise, promise is generated by ES6 to solve asynchronous callbacks. It uses the then chain to solve the problem of multi-level callbacks. I combine async/await to further optimize it.
  • What is Async/Await?
    • async/await is implemented based on Promise and cannot be used for normal callback functions.
    • async/await, like Promise, is non blocking.
    • Async is the abbreviation of "asynchronous", while await can be regarded as the abbreviation of async wait. So it should be well understood that async is used to declare that a function is asynchronous, while await is used to wait for the execution of an asynchronous method to complete.

summary

In fact, we have a simpler way to implement the above code. Here we use the idea of stream

const fs = require('fs');
const Koa = require('koa');
const app = new Koa();
const static = require('koa-static');
const main = ctx =>{
    ctx.response.type = 'html';
    ctx.response.body = fs.createReadStream('./template.html');
}
app.use(static('./'));
app.use(main);
app.listen(3000,function(){
    console.log('Successfully started on port 3000')
});
Copy code

As you can see, the use of streams is more powerful. I won't go over it here.

Write it at the back

At present, I am still a junior student. If there are some mistakes, welcome to correct them, and also welcome to communicate with you, hope to grow up with you!

Tags: Programming Javascript

Posted on Sun, 17 May 2020 17:41:03 -0700 by wes007