Bruce Gust
asked on
Where is "Unexpected end of JSON input" coming from?
Here's my code:
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\expr ess_tutori al\models\ product.js :18:25)
at FSReqWrap.readFileAfterClo se [as oncomplete] (internal/fs/read_file_con text.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!
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;
}
};
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\expr
at FSReqWrap.readFileAfterClo
[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!
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.
[{ "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
maybe a carriage return ? remove it