1

i am trying to read external json file with fs and then log it but it does not work. In my json file i have only one array to read :

{
"tags": [ "blah", "blah1", "etc..."
        ]
}

and i am using async readFile function to read it

...
const tagsjson = require('../tags.json');
var tags;
...

 fs.readFile(tagsjson, 'utf8', function(err,data){
  if(err) throw err;

  tags = data;
})
 console.log(tags)

i don't know what is problem i tried JSON.parse(data) but it did not work too, and i am using raw data because, i want to send that tags to client after i read it.

ilia
  • 339
  • 8
  • 23
  • 1
    _... but it does not work_ What does not work? Do you get any errors? Or do you have trouble due to the asynchronous call of `readFile` (since `console.log(tags)` is not withing the callback)? – pzaenger Apr 04 '19 at 12:51
  • i am using try catch and it logged this in browser console, `Failed to load resource: the server responded with a status of 500 (Internal Server Error)` – ilia Apr 04 '19 at 12:52
  • The filename should be e.g. a string, `const tagsjson = require('../tags.json');` looks kinda wrong. Like `fs.readFile('../tags.json', 'utf8', (err, data) => { ...`. – pzaenger Apr 04 '19 at 12:55
  • oh it logged this `The system cannot open the device or file specified` let me try what you told me – ilia Apr 04 '19 at 12:58

2 Answers2

3

You're reading file in a wrong way , Here is the mistake

const tagsjson = require('../tags.json');

what require will return actually what exported which will return an object , And readFile function takes its first argument a string

fs.readFile('../tags.json', 'utf8', function(err,data){
  if(err) throw err;

As well as for dealing with asynchronous operations you would deal with two options

  • Callback
  • Promises

For promises

const promise = new Promise((resolve, reject) => {
  fs.exists('../tags.json', (exists) => {
     if (exists) {
        fs.readFile('../tags.json', (err, data) => { 
          if(err) {
            console.log(err);
            reject(err);
            } else resolve(data);
         });
       } else {
         reject('File Does Not Exist!');
       }
   });
 });

promise
  .then(data => {
    console.log(data);
  })
  .catch(err => {
    console.log(err);
  });
Abdulrahman Falyoun
  • 3,676
  • 3
  • 16
  • 43
1

As you're using async file reading, you'll have to use your tags variable inside the callback function. You also have to pass the filename in the readFile function :

Asynchronous :

var tags;
fs.readFile("../tags.json", 'utf8', function (err, data) {
   if (err) throw err;

   tags = data;
   console.log(tags);
});

Synchronous :

var tags;
tags = fs.readFileSync("../tags.json", 'utf8');
console.log(tags);
Dylan M.
  • 37
  • 1
  • 1
  • 11
  • how will i be able to send it to client if i can't use tags outside my callback function – ilia Apr 04 '19 at 13:07
  • You can put the rest of the code inside this callback, are you can use Promises to be sure to execute the rest of the code after the file has been read – Dylan M. Apr 04 '19 at 13:13
  • Or you can use the readFileSync function to block execution of the code and use you tags var like you wanted in your code – Dylan M. Apr 04 '19 at 13:22
  • 1
    it's never a good idea to recommend a synchronous approach in Node.js. If this is used on a server **never use a sync method if there's an async one** – Marcos Casagrande Apr 04 '19 at 13:28
  • I know and I totally agree with you, but it exists and in a first time, if he doesn't know how to use promises, it can be a solution – Dylan M. Apr 04 '19 at 13:30
  • i know how to use promises, and that's why admitted in my question that i used async readFile, i am not a big fan of sync, and it would be my last alternative to use sync in I/O – ilia Apr 04 '19 at 14:12