Writing in the front

The author recently encountered an interesting problem, as we all know there are two types of file reads

fs.readFileSync(); // Read synchronously
fs.readFile(); // Read asynchronously
Copy the code

Promise is a solution for asynchronous programming, so can we encapsulate a Promise version of readFile?

primers

Let’s take a look at Teacher Ruan Yifeng’s explanation about javascript being single threaded

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

One of the features of the JavaScript language is single threading, that is, you can only do one thing at a time. When you make a call, you have to wait for the previous task to complete before the next task can be executed. This execution mode is called synchronization. Single threading means that all tasks need to be queued until the first one is finished before the next one can be executed. If the first task takes a long time, the second task has to wait forever. The designers of the JavaScript language realized that the main thread could simply ignore the IO device, suspend the pending task and run the next one first. Wait until the IO device returns the result, then go back and continue the pending task. Therefore, all tasks can be divided into two types, one is synchronous task, the other is asynchronous task.

What is synchronous programming?

Synchronous programming means that the computer executes the code line by line in sequence, and the execution of the current code task will block the execution of the subsequent code.

What is asynchronous programming?

Asynchronous programming means that after a call is made, the call returns directly. The caller does not get the result immediately, but does not block and can continue to perform subsequent operations. In a word

Programs do not have to be executed from top to bottom in code order

Required documents

This is the template.html file we are importing

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

Style and JS can be written by yourself, I wrote a little rough, on the local preview looks like this:

Synchronous reading

Now we read the 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 headers
    const html = fs.readFileSync('./template.html'.'utf-8');    // Read synchronously
    // console.log(html);
    ctx.response.body =html;
}
app.use(static('/'));
app.use(main); 
app.listen(3000);
Copy the code

This is synchronous writing, and it blocks. Very time consuming for high concurrency.

Asynchronous reading

Now let’s use the asynchronous method 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 headers
    // Encapsulate 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 the code

preview

Some explanation of the above code

  • Koa-static was introduced to handle static resources
  • Promise, Promise was developed for asynchronous callbacks by ES6. It uses then chain to solve the problem of multi-layer callbacks. I combined async/await to further optimize it.
  • What is the Async/Await?
    • Async /await is implemented based on promises and cannot be used for normal callback functions.
    • Async /await, like Promise, is non-blocking.
    • Async is short for ‘asynchronous’ and await can be thought of as short for async wait. So it makes sense that async is used to declare that a function is asynchronous and await is used to wait for an asynchronous method to complete.

conclusion

For the above code, there is actually a simpler way to implement, using the idea of a 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('Started successfully on port 3000')});Copy the code

As you can see, the use of streams is much more powerful. I won’t go into too much detail here.

Write in the back

I am still a junior student, if there are corresponding mistakes, welcome to correct, but also welcome everyone can exchange problems together, I hope to grow up with you!