- Mastering Node.js(Second Edition)
- Sandro Pasquali Kevin Faaborg
- 262字
- 2021-07-02 19:28:40
Optimized JavaScript
The JavaScript language is in constant flux, and some major changes and improvements have begun to find their way into native compilers. The V8 engine used in the latest Node builds supports nearly all of the latest features. Surveying all of these is beyond the scope of this chapter. In this section, we'll mention a few of the most useful updates and how they might be used to simplify your code, helping to make it easier to understand and reason about, to maintain, and perhaps even become more performant.
We will be using the latest JavaScript features throughout this book. You can use Promises, Generators, and async/await constructs as of Node 8.x, and we will be using those throughout the book. These concurrency operators will be discussed at depth in Chapter 2, Understanding Asynchronous Event-Driven Programming, but a good takeaway for now is that the callback pattern is losing its dominance, and the Promise pattern in particular is coming to dominate module interfaces.
In fact, a new method util.promisify was recently added to Node's core, which converts a callback-based function to a Promise-based one:
const {promisify} = require('util');
const fs = require('fs');
// Promisification happens here
let readFileAsync = promisify(fs.readFile);
let [executable, absPath, target, ...message] = process.argv;
console.log(message.length ? message.join(' ') : `Running file ${absPath} using binary ${executable}`);
readFileAsync(target, {encoding: 'utf8'})
.then(console.log)
.catch(err => {
let message = err.message;
console.log(`
An error occurred!
Read error: ${message}
`);
});
Being able to easily promisify fs.readFile is very useful.
Did you notice any other new JavaScript constructs possibly unfamiliar to you?
- 計(jì)算機(jī)網(wǎng)絡(luò)與通信(第2版)
- Mastering Machine Learning for Penetration Testing
- 物聯(lián)網(wǎng)+BIM:構(gòu)建數(shù)字孿生的未來(lái)
- 網(wǎng)絡(luò)安全應(yīng)急響應(yīng)技術(shù)實(shí)戰(zhàn)
- 語(yǔ)音信號(hào)處理及Blackfin DSP實(shí)現(xiàn)
- 紅藍(lán)攻防:構(gòu)建實(shí)戰(zhàn)化網(wǎng)絡(luò)安全防御體系
- 轉(zhuǎn)化:提升網(wǎng)站流量和轉(zhuǎn)化率的技巧
- 深入理解Nginx:模塊開(kāi)發(fā)與架構(gòu)解析
- 數(shù)據(jù)血緣分析原理與實(shí)踐
- 網(wǎng)絡(luò)安全之道
- 數(shù)字王國(guó)里的虛擬人:技術(shù)、商業(yè)與法律解讀
- RestKit for iOS
- Microservices Development Cookbook
- Hands-On Cloud:Native Microservices with Jakarta EE
- 物聯(lián)網(wǎng)商業(yè)設(shè)計(jì)與案例