簡體   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