首页 > 解决方案 > 如何在 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”将对这些图片应用灰度。我知道这是因为这两个函数同时运行导致了问题。那么我如何实现承诺来解决这个问题。我知道我可以使用“同步”版本的功能。我只想知道如何在承诺中做到这一点。

标签: javascriptnode.jsasynchronouspromise

解决方案


您可以使用流完成事件来确定文件解压缩何时完成。然后我们可以使用 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');

推荐阅读