Comment passer les données de lecture de Wait readFile à writeFile dans le module fs de node.js?

Oct 02 2020

Dans ce code, le fichier est ouvert et lu avec succès.

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

Comment extraire les données de Wait of readFile et les transmettre à writeFile?

La façon dont j'ai écrit la fonction writeFile produit l'erreur suivante:

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

Réponses

1 gurisko Oct 02 2020 at 18:48

Peu de problèmes que je peux voir:

  • il existe un mélange de syntaxes - async/awaittout en fournissant également des rappels aux fsappels;
  • pas besoin d'appeler fs.openavant fs.readFile;
  • il n'y a pas de données à écrire dans fs.writeFile[ docs ];
  • il devrait y avoir await-ing à la fin;
  • et la finale (l'erreur réelle signalée) - il devrait y avoir un try...catchbloc pour attraper et réagir à toute erreur qui se produit.

Exemple d'implémentation:

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