javascript - 如何在 node.js 函数中应用 Promise
问题描述
我正在尝试编写一个可以解压缩 zip 文件、读取文件中的图像并对它们应用灰度的程序。
现在我有这两个功能:
var fs = require('fs'),
PNG = require('pngjs').PNG
const unzipper = require('unzipper')
PNG = require('pngjs').PNG
const dir = __dirname + "/";
const myFile = (fileName) => {
let createdFile = dir + fileName
fs.createReadStream(createdFile)
.pipe(unzipper.Extract({ path: 'myfile' }));
console.log('file unzipped')
}
myFile("myfile.zip")
function applyFilter(Name) {
fs.readdir(Name, 'utf-8', (err, data) => {
if (err) {
console.log(err)
} else {
data.forEach(function (file) {
if (file.includes('png')) {
let greyPNG = (__dirname + '/' + 'myfile' + '/' + file)
console.log (greyPNG)
fs.createReadStream(greyPNG)
.pipe(new PNG({
colorType: 0,
}))
.on('parsed', function () {
this.pack().pipe(fs.createWriteStream(__dirname + "/" + "myfile" + "/" + file));
});
}
})
}
})
}
applyFilter ('myfile')
这两个函数单独工作正常,但是,如果我注释掉“applyFilter”,它不会一起运行。将解压缩一个 zip 文件。如果目录中有文件,“applyFilter”将对这些图片应用灰度。我知道这是因为这两个函数同时运行导致了问题。那么我如何实现承诺来解决这个问题。我知道我可以使用“同步”版本的功能。我只想知道如何在承诺中做到这一点。
解决方案
您可以使用流完成事件来确定文件解压缩何时完成。然后我们可以使用 promises 和 async / await 来确保我们不会在文件准备好之前尝试应用过滤器。
const fs = require('fs');
const PNG = require('pngjs').PNG;
const unzipper = require('unzipper');
const dir = __dirname + "/";
function unzipFile(fileName, outputPath) {
return new Promise((resolve, reject) => {
let createdFile = dir + fileName
let stream = fs.createReadStream(createdFile)
.pipe(unzipper.Extract({ path: outputPath }));
stream.on('finish', () => {
console.log('file unzipped');
resolve(outputPath);
});
});
}
function applyFilter(Name) {
fs.readdir(dir, 'utf-8', (err, data) => {
if (err) {
console.log(err)
} else {
data.filter(file => file.includes("png")).forEach(file => {
let greyPNG = (__dirname + '/' + Name + '/' + file)
console.log (greyPNG)
fs.createReadStream(greyPNG)
.pipe(new PNG({
colorType: 0,
}))
.on('parsed', function () {
this.pack().pipe(fs.createWriteStream(greyPNG));
});
})
}
})
}
async function unzipAndApplyFilter(zipFile, outputPath) {
await unzipFile(zipFile, outputPath); // Wait until unzip is complete.
applyFilter(outputPath);
}
unzipAndApplyFilter('myfile.zip', 'myfile');
推荐阅读
- javascript - Angular 7过滤器下拉值
- c# - Gmail API:使用包含变音符号的邮件地址会导致 SMTPEception:客户端或服务器仅配置为具有 ASCII 本地部分的地址
- makefile - 为什么我的 makefile 永远不会停止构建?
- javascript - MS Edge 随机不加载脚本
- node.js - Swagger 模块中的前缀 url
- reactjs - 表单中的多个输入元素 - React
- python - 从多个 Python 文件中删除特定的代码行
- python - Python在具有可变长度的对象构造函数中创建二维数组
- xamarin.forms - 升级到 4.5.0.396 后 Xamarin.iOS 项目缺少引用错误
- javascript - 动画不同步,如何实现流畅的动画?