【问题标题】:How to pass read data from await readFile to writeFile in fs module of node.js?如何将读取数据从等待 readFile 传递到 node.js 的 fs 模块中的 writeFile?
【发布时间】:2020-10-02 20:08:20
【问题描述】:

在这段代码中,文件被成功打开和读取。

var objFs = require('fs')

async function openFile() {
    await objFs.open('new.js', 'r', (argError, argFD) => {
        if (argError)
            throw -1
        else
            console.log("File opened!")
    })

    // This object is the promise.                  
    const objReadResult = await objFs.readFile('new.js', (argError, argData) => {
        if (argError)
            throw 2
        else
            console.log('File read!')
    })

    await objFs.writeFile('new.js', (argError, objReadResult) => {
                                  try
                                    {
                                        if( argError )
                                            throw argError
                                        else
                                            console.log("File written")
                                    }
                                    catch( arg )
                                    {
                                        console.log(arg)
                                    }        
    })


}

openFile()

readFile的await中提取数据并传递给writeFile的方法是什么?

我编写 writeFile 函数的方式产生了以下错误:

(node:21737) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
    at maybeCallback (fs.js:145:9)
    at Object.writeFile (fs.js:1332:14)
    at openFile (/home/sulakshana/Documents/nodejs/programs/async_await.js:29:14)
(node:21737) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:21737) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
File opened!
File read!
 

【问题讨论】:

标签: javascript node.js async-await


【解决方案1】:

我能看到的几个问题:

  • 有多种语法 - async/await,同时还提供对 fs 调用的回调;
  • 无需在fs.readFile之前调用fs.open
  • fs.writeFile[docs]中没有要写入的数据;
  • 最后应该有await-ing;
  • 和最终的(报告的实际错误) - 应该有 try...catch 块来捕获并响应发生的任何错误。

示例实现:

const fs = require('fs').promises;

async function openFile() {
    const objReadResult = await fs.readFile('new.js');
    console.log('File read!');
    await fs.writeFile('new.js', /* PROVIDE DATA TO WRITE */);
    console.log('File written');
}

(async () => {
    try {
        await openFile();
        console.log('Program is done');
    } catch (err) {
        console.error(err);
    }
})();

【讨论】:

  • writeFile的数据应该是readFile读取的文件内容。通过它的方法是什么? objReadResult.data - 我应该通过这个吗?
  • @Aquarius_Girl 你可以直接传objReadResult。由于我们没有在readFile 中指定编码,所以objReadResult 应该是BufferBuffer 类型被 fs.writeFile 接受。总结一下:await fs.writeFile('new.js', objReadResult);
  • 这行得通。最后。我需要阅读更多关于 await 和 aysnc 的信息。感谢您的耐心等待。
猜你喜欢
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2018-01-13
  • 1970-01-01
  • 2018-08-18
  • 2020-02-08
相关资源
最近更新 更多