Aquarius_Girl
Aquarius_Girl

Reputation: 22946

How to pass read data from await readFile to writeFile in fs module of node.js?

In this code, file is being opened and read successfully.

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()

What is the way to extract the data from await of readFile and pass it to writeFile?

The way I have written the writeFile function is producing the following error:

(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!
 

Upvotes: 0

Views: 619

Answers (1)

gurisko
gurisko

Reputation: 1182

Few issues I can see:

  • there is a mix of syntaxes - async/await while also providing callbacks to the fs calls;
  • no need to call fs.open before fs.readFile;
  • there are no data to be written in fs.writeFile [docs];
  • there should be await-ing at the end;
  • and the final (the actual error reported) - there should be try...catch block to catch and react to any errors that occur.

Example implementation:

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);
    }
})();

Upvotes: 1

Related Questions