This article brings you an example explanation of asynchronous processing under ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Preface
Let’s take finding the largest file in a specified directory as an example to experience the
callback function -> Promise -> Generator -> Async
Changes in asynchronous processing methods.
API Introduction
In order to implement this function, we need to use several Nodejs APIs, so let’s briefly introduce them.
fs.readdir
The readdir method is used to read a directory and returns an array containing files and directories.
fs.stat
The parameter of the stat method is a file or directory, and it generates an object that contains specific information about the file or directory. In addition, this object also has an isFile() method that can determine whether it is a file or a directory being processed.
Idea analysis
Our basic implementation idea is:
Use fs.readdir
to obtain the content information of the specified directory
Loop through the content information and use fs.stat
to obtain the specific information of the file or directory
Save the specific information Get up
After all are stored, filter the file information
Traverse and compare to find the largest file
Get and return the largest file
Then let’s go directly to the code.
var fs = require('fs'); var path = require('path'); function findLargest(dir, cb) { // 读取目录下的所有文件 fs.readdir(dir, function(er, files) { if (er) return cb(er); var counter = files.length; var errored = false; var stats = []; files.forEach(function(file, index) { // 读取文件信息 fs.stat(path.join(dir, file), function(er, stat) { if (errored) return; if (er) { errored = true; return cb(er); } stats[index] = stat; // 事先算好有多少个文件,读完 1 个文件信息,计数减 1,当为 0 时,说明读取完毕,此时执行最终的比较操作 if (--counter == 0) { var largest = stats .filter(function(stat) { return stat.isFile() }) .reduce(function(prev, next) { if (prev.size > next.size) return prev return next }) cb(null, files[stats.indexOf(largest)]) } }) }) }) }
The usage method is:
// 查找当前目录最大的文件 findLargest('./', function(er, filename) { if (er) return console.error(er) console.log('largest file was:', filename) });
var fs = require('fs'); var path = require('path'); var readDir = function(dir) { return new Promise(function(resolve, reject) { fs.readdir(dir, function(err, files) { if (err) reject(err); resolve(files) }) }) } var stat = function(path) { return new Promise(function(resolve, reject) { fs.stat(path, function(err, stat) { if (err) reject(err) resolve(stat) }) }) } function findLargest(dir) { return readDir(dir) .then(function(files) { let promises = files.map(file => stat(path.join(dir, file))) return Promise.all(promises).then(function(stats) { return { stats, files } }) }) .then(data => { let largest = data.stats .filter(function(stat) { return stat.isFile() }) .reduce((prev, next) => { if (prev.size > next.size) return prev return next }) return data.files[data.stats.indexOf(largest)] }) }
The usage method is:
findLargest('./') .then(function(filename) { console.log('largest file was:', filename); }) .catch(function() { console.log(error); });
var fs = require('fs'); var path = require('path'); var co = require('co') var readDir = function(dir) { return new Promise(function(resolve, reject) { fs.readdir(dir, function(err, files) { if (err) reject(err); resolve(files) }) }) } var stat = function(path) { return new Promise(function(resolve, reject) { fs.stat(path, function(err, stat) { if (err) reject(err) resolve(stat) }) }) } function* findLargest(dir) { var files = yield readDir(dir); var stats = yield files.map(function(file) { return stat(path.join(dir, file)) }) let largest = stats .filter(function(stat) { return stat.isFile() }) .reduce((prev, next) => { if (prev.size > next.size) return prev return next }) return files[stats.indexOf(largest)] }
Usage method is:
co(findLargest, './') .then(function(filename) { console.log('largest file was:', filename); }) .catch(function() { console.log(error); });
var fs = require('fs'); var path = require('path'); var readDir = function(dir) { return new Promise(function(resolve, reject) { fs.readdir(dir, function(err, files) { if (err) reject(err); resolve(files) }) }) } var stat = function(path) { return new Promise(function(resolve, reject) { fs.stat(path, function(err, stat) { if (err) reject(err) resolve(stat) }) }) } async function findLargest(dir) { var files = await readDir(dir); let promises = files.map(file => stat(path.join(dir, file))) var stats = await Promise.all(promises) let largest = stats .filter(function(stat) { return stat.isFile() }) .reduce((prev, next) => { if (prev.size > next.size) return prev return next }) return files[stats.indexOf(largest)] }
Usage method is:
findLargest('./') .then(function(filename) { console.log('largest file was:', filename); }) .catch(function() { console.log(error); });
https://github.com/mqyqingfeng/Blog
The above is the detailed content of Example explanation of asynchronous processing under ES6. For more information, please follow other related articles on the PHP Chinese website!