在node.js的fs模块中,如何将读取的数据从wait-readFile传递给writeFile



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

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的等待中提取数据并将其传递给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!

我能看到的几个问题:

  • 有一个混合语法-async/await,同时还提供对fs调用的回调
  • 在CCD_ 4之前不需要调用CCD_ 3
  • fs.writeFile[docs]中没有要写入的数据
  • 最后应该有CCD_ 6-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);
}
})();

最新更新