i have simple form validation, what i am doing is: read json file, get property from it (Array) then check if it contains every single element of user generated array and nothing more, for example:

[1,2,3,4,5] (json file array)
[1,2,3,4,5,6] (U.G array) //it must return false

so i am using this code for implementing this:

 const contains = (arr1, arr2) => {
  arr2.every(v => arr1.indexOf(v) !== -1)
   var match;
   fs.readFile('../tags.json', 'utf8', (err, data)=>{

     var JsonData = JSON.parse(data);
     var tagsArray = JsonData.tags;
     if(tagsArray instanceof Array){
       console.log('tagsArray is array')
      if(!contains(tagsArray, tags)){
        match = false
        match = true
     console.log(match + ' blah1')


   console.log(match + ' blah2')
 if(match == false){
    return res.status(409).send({
      message: 'Do not provide your own tags'

but it is returning false everytime because contains(tagsArray, tags) are undefined everytime. so what is the clue for this?

2 Answers

Nils Alexandre Bergsten On

The match variable inside your fs.readFile callback is the same variable match declared in the outer scope, thanks to closures. Therefore, the problem is in the inner logic.

xiayouxue On

see fs.readFile document: Asynchronously reads the entire contents of a file.

so the execution order is:

execution order

or you can use fs.readFileSync()