Search code examples
javascriptexpressecmascript-6

Unexpected end of JSON input when requiring a JSON file


When using fs.writeFile I create a JSON file that looks like:

[{"schoolname":"Scottsdale","StudentFirst":"john","StudentLast":"smith","grade":"2","email":"[email protected]","ParentLast":"Smith","ParentFirst":"John"}]

Except right after when I require the same file I get the error:

Unexpected end in JSON input

I've done this same thing before but using bigger data and it seemed to work fine.

await fs.writeFile(`./${fileName}.json`, 
JSON.stringify(result.recordsets[0]), function(err) {
     if(err) {
           return console.log(err)
     }
})
const file = require(`./${fileName}.json`)

Expected results should return the JSON above so I can have a copy of the file and iterate through it.


Solution

  • The error is the result of requiring an empty JSON file. The JSON file is empty because fs.writeFile is asynchronous, and you're using await improperly.

    1. You need to use await inside of an async function
    2. You can only use await with promises, not callbacks

    Option 1: use fs.writeFileSync

    fs.writeFileSync(
      `./${fileName}.json`, 
      JSON.stringify(result.recordsets[0])
    )
    const file = require(`./${fileName}.json`)
    

    Option 2: wrap fs.writeFile in a promise

    (async () => {
      await new Promise((resolve, reject) => {
        fs.writeFile(
          `./${fileName}.json`, 
          JSON.stringify(result.recordsets[0]),
          function(err) {
            if (err) {
              reject()
              return console.log(err)
            }
            resolve()
          }
        )
      });
      const file = require(`./${fileName}.json`)
    })();