We read the file asynchronously.

fs.readFile('./path', function(err, file){}) 

In callback, we get the result. There is a need to perform various manipulations with the contents of the file, for example:

 function addOne(file){console.log(file+'1')} function addSmt(file, smt){console.log(file+smt)} 

In other words, the file should be read once and only once, and then work with its contents as needed.

  • one
    So work. Who prohibits? Or are you saying that you need to work with the file outside of a callback? Then save the file to a global variable. - alexlz
  • I myself thought about the global variable, but it is not according to GOST. Here the whole difficulty is to read the file only once, and not with every call to addOne for example. And even if so: var globVar = ''; \ n fs.readFile (path, f (err, file) {globVar = file}); \ n addOne (globVar); \ n How to make addOne () wait for globVar? - alvoro
  • It is not very clear what exactly you want. But maybe you should replace fs.readFile with her fs.readFileSync brother - alexlz
  • Something does not work out the idea to formulate). I used fs.readFile for an example. The project will have MongoClient, which returns a database object in the same way as fs.readFile returns a file. That is, I need to create a connection once, and then work with the fact that I returned the callback and I did not find the synchronous option in the documentation. - alvoro
  • Thanks for the help. I will use a global variable, and wait through settimeout, which is true, in my opinion, I am a crutch))) - alvoro

0