繁体   English   中英

为什么“读取 2 个文件并返回差异”在 NodeJS 中不起作用?

[英]Why "read 2 files and return diff" doesn't work in NodeJS?

我需要一个函数,它接受 2 个文件名,读取它们并返回一个差异。 这是我写的,但它确实根据我的需要返回布尔值。

const fs = require('fs')
const util = require('util')

const readFile = util.promisify(fs.readFile)
const access = util.promisify(fs.access)

/**
 * if exists, read the file (async)
 * @param {*} fileName
 * @returns Promise that if resolved will produce file contents
 */

async function 
verifyAndRead (fileName) {
    let _txt = null
    try {
        await access(fileName)
        .then(() => readFile(fileName))
        .then((txt) => _txt = txt.toString())
    }
    catch (e) {
        console.error(`verifyAndRead(): ${e.stack}`)
    }
    // console.log(`foo(): ${_txt}`)
    return _txt
}

async function 
match (file1, file2) {
    // logger.trace(`match ('${file1}', '${file2}')`)

    let a = await verifyAndRead(f1)
    let b = await verifyAndRead(f2)

    return a === b
}

在 match() 中,a 和 b 都被解析。 即 console.log() 打印文件的内容,所以它们是可用的,所以 return 语句应该返回 diff (true/false) 但它返回一个 Promise。 为什么? 我需要一个布尔值。 此函数是 API/模块的一部分,其他用户将使用该 API/模块来开发测试用例/脚本,并且主要不是 javascript 开发人员,因此我需要为他们保持简单。 这的典型用途是

if (match(<expected_output>, <current_output>)) { logger.log('Test passed.') }

我想避免测试人员在他们的脚本中使用“await”或“then()”等。

因为a === b返回一个 Promise,我进一步尝试替换

return a === b

let c = await (() => {
    a === b
})()

return c

希望得到一个布尔值,但这也无济于事。

在尝试了很多事情之后,看起来唯一的方法是同步读取文件并进行比较,但我想尽可能多地以 Node.js 的方式来做。

有谁知道它是否/如何异步完成? 我错过了什么吗?

我认为与其避免使用 'await' 或 'then()',您应该使用 promise 的特性。 尝试像这样更改匹配功能:

const fs = require('fs')
const util = require('util')

const readFile = util.promisify(fs.readFile)
const access = util.promisify(fs.access)

async function
verifyAndRead (fileName) {
    let _txt = null
    try {
        await access(fileName)
            .then(() => readFile(fileName))
            .then((txt) => _txt = txt.toString())
    }
    catch (e) {
        console.error(`verifyAndRead(): ${e.stack}`)
    }
    return _txt
}

async function match (f1, f2) {
    return new Promise(resolve => {
        Promise.all([verifyAndRead(f1), verifyAndRead(f2)]).then((values) => {
            resolve(values[0] === values[1]);
        });
    });
}

match('package.json', 'package-lock.json').then((result) => {
    if (result) {
        // if match do your stuff
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM