W
W
wufapexef2017-10-06 18:15:11
Node.js
wufapexef, 2017-10-06 18:15:11

Why doesn't the callback in fs.readFile fire?

Why does err not work that the file does not exist ( file does not exist), but throws another error related to the else code

SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)

fs.readFile(file, 'utf8', (err, snapshot) => {
    if (err) {
      axios.get(url)
        .then((res) => {
          let firstSnapshot = { data: '', date: '' }
          let $ = cheerio.load(res.data)
          firstSnapshot.data = $(selector).html().replace(/\s/g, '')
          firstSnapshot.date = new Date(Date.now())
          fs.writeFile(file, JSON.stringify(firstSnapshot, null, 2), (err) => {
            return console.log('First snapshot file created!')
          })
        })
    }
    snapshot = JSON.parse(snapshot)
    console.log(snapshot.date)
  })

In general, what is the best way to accomplish such a task: to request or read a file, but if it does not exist, then create it and then read it again?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2017-10-06
@wufapexef

Because after checking the error, they try to parse a non-existent file:
snapshot = JSON.parse(snapshot)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question