Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

Where is "Unexpected end of JSON input" coming from?

Here's my code:

const fs = require("fs");
const path = require("path");

module.exports = class Product {
  constructor(t) {
    this.title = t;
  }

  save() {
    const p = path.join(
      path.dirname(process.mainModule.filename),
      "data",
      "products.json"
    );
    fs.readFile(p, (err, fileContent) => {
      let products = [];
      if (!err) {
        products = JSON.parse(fileContent);
      }
      products.push(this);
      fs.writeFile(p, JSON.stringify(products), err => {
        console.log(err);
      });
    });
  }

  static fetchAll() {
    return products;
  }
};

Open in new window


The error that I'm getting is:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at fs.readFile (C:\wamp\www\adm\node\express_tutorial\models\product.js:18:25)
    at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)
[nodemon] app crashed - waiting for file changes before starting...

This is line #18: products = JSON.parse(fileContent);

Two questions: First of all, what am I missing that would result in the error that I'm getting?

Secondly, what is "18:25?" I'm referring to the actual error message. "18," I'm assuming, is line #18, but what is "25?"

Thanks!
Avatar of leakim971
leakim971
Flag of Guadeloupe image

25 is the position on the line
maybe a carriage return ? remove it
SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bruce Gust

ASKER

Julian, it's a blank page. There isn't any code, characters, tick marks - nothing.
I don't understand - your code is reporting invalid JSON - where is that coming from?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The product.JSON file looks like this:

[{ "title": " Book Title" }]

But at one point, I deleted everything so, while the file existed, it had absolutely no text or characters in it. When I replaced the empty page with what you see above, the error went away.
replaced the empty page with what you see above AND add a space and/or carriage return to got the error come back