1

I have problem with function in function in node.js

function function_1() {
    var fs = require('fs');

    fs.readFile('date.json', function(err, content) {
        if (err) throw err;

        var parseJson = JSON.parse(content);

        fs.writeFile('date.json', JSON.stringify(parseJson), function(err) {
            if (err) throw err;
        })
    })

    return parseJson;
}

I had no idea how to return value from the file out of my reading function.I tried many things but I failed.I am just starting with node.js.I will be thankfull for every advice.

Magiczne
  • 1,586
  • 2
  • 15
  • 23
Bartosz
  • 11
  • 2

1 Answers1

-2

First you may want to add your requirement as a constant at the beginning of the file, that's not mandatory but it's a nice best practice :

const fs = require('fs');

next for your problem, just declare a variable on the outside scope and fill it with the file content :

const fs = require('fs');  

function function_1() {
     var parseJson
     fs.readFile('date.json',function(err,content){
       if(err) throw err;
       parseJson = JSON.parse(content);
     })    
    
     return parseJson;
}

Or as @Pointy mentioned you can just use readFileSync that does not require a callback:

const fs = require('fs');  

function function_1() {
     return JSON.parse(fs.readFileSync('date.json'));
}
Bastien
  • 994
  • 11
  • 25
  • 1
    "just declare a variable on the outside scope and fill it with the file content" — That doesn't work! – Quentin Sep 14 '20 at 20:27