admin管理员组

文章数量:1332377

I am new to node js and using MVC pattern in my project so when I am trying to add products to my cart.json file I am facing the issue

routes file

const Product = require('../models/product');
const Cart = require('../models/cart')

exports.postcart = (req,res,next) => {
    const proid = req.params.productcartid
    Product.findbyid(proid).then(function(value) {
        console.log(value.price)    // prints the price correctly so the producted is received as an argument
        Cart.addProduct(proid, value.price)
    })
}

Product model

  module.exports = class Product {
      // constructor function here 

      save() {
          //saving the products here, works fine
      }

      static findbyid(id) {
          const p = path.join(path.dirname(process.mainModule.filename), 'data', 'products.json') 
          return new Promise((resolve, reject) => {
               fs.readFile(p, (err, data) => {
                   const allproducts = JSON.parse(data)
                   const result = allproducts.find(p => p.id === id)
                   return resolve(result)   
               })
          })
      } 
  }

Cart model

module.exports = class Cart {
static addProduct(id, price) {
    const p=path.join(path.dirname(process.mainModule.filename),
'data','cart.json')
    fs.readFile(p, (error, file) => {
        console.log('sgdf',id);
        let cart = {
            products: [],
            totalPrice: 0
        };
        if(!error) {
            console.log('inside error') //prints in console
            cart = JSON.parse(file);
        }
        console.log('outside error') //does not output this and anything below from here too doesn't prints in the console

        const existingProductIndex = cart.products.findIndex(p => 
p.id === id);
        console.log('dghjhjghfg',existingProductIndex) ////does not output this 
        const existingProduct = 
cart.products[existingProductIndex];
        if(existingProduct) {
            existingProduct.qty += 1;
        }
        else {
            cart.products.push({
                id,
                qty: 1
            });
        }
        cart.totalPrice += Number(price);
        console.log(cart);
        fs.writeFile(p, JSON.stringify(cart), error => {
            if(error) return console.error(error);
        });
    });
}

};

cart.js

const fs=require('fs')
const path=require('path')
module.exports = class Cart {

static addProduct(id, price) {
    const 
 p=path.join(path.dirname(process.mainModule.filename),
'data','cart.json')
    fs.readFile(p, (error, file) => {
        console.log('sgdf',id);
        let cart = {
            products: [],
            totalPrice: 0
        };
        if(!error) {
            console.log('insdie error')
            console.log(file)
            cart = JSON.parse(file)
        }
        console.log('outside error')

        const existingProductIndex = cart.products.findIndex(p => p.id 
  === id);
        console.log('dghjhjghfg',existingProductIndex)
        const existingProduct = cart.products[existingProductIndex];
        if(existingProduct) {
            existingProduct.qty += 1;
        }
        else {
            cart.products.push({
                id,
                qty: 1
            });
        }
        console.log('adsgfdgfh')
        cart.totalPrice += Number(price);
        console.log(cart);
        fs.writeFile(p, JSON.stringify(cart), error => {
            if(error) return console.error(error);
        });
    });
    }
   };

The error i am facing is

undefined:1



SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at /Users/ratnabhkumarrai/Desktop/max-project/models/cart.js:15:29
at FSReqCallback.readFileAfterClose [as onplete] 
(internal/fs/read_file_context.js:61:3)

In my Cart models when i try to console log and see i find that only my half of the code is executed the console log that i tried below does not get executed....What am i doing wrong here ?

I am new to node js and using MVC pattern in my project so when I am trying to add products to my cart.json file I am facing the issue

routes file

const Product = require('../models/product');
const Cart = require('../models/cart')

exports.postcart = (req,res,next) => {
    const proid = req.params.productcartid
    Product.findbyid(proid).then(function(value) {
        console.log(value.price)    // prints the price correctly so the producted is received as an argument
        Cart.addProduct(proid, value.price)
    })
}

Product model

  module.exports = class Product {
      // constructor function here 

      save() {
          //saving the products here, works fine
      }

      static findbyid(id) {
          const p = path.join(path.dirname(process.mainModule.filename), 'data', 'products.json') 
          return new Promise((resolve, reject) => {
               fs.readFile(p, (err, data) => {
                   const allproducts = JSON.parse(data)
                   const result = allproducts.find(p => p.id === id)
                   return resolve(result)   
               })
          })
      } 
  }

Cart model

module.exports = class Cart {
static addProduct(id, price) {
    const p=path.join(path.dirname(process.mainModule.filename),
'data','cart.json')
    fs.readFile(p, (error, file) => {
        console.log('sgdf',id);
        let cart = {
            products: [],
            totalPrice: 0
        };
        if(!error) {
            console.log('inside error') //prints in console
            cart = JSON.parse(file);
        }
        console.log('outside error') //does not output this and anything below from here too doesn't prints in the console

        const existingProductIndex = cart.products.findIndex(p => 
p.id === id);
        console.log('dghjhjghfg',existingProductIndex) ////does not output this 
        const existingProduct = 
cart.products[existingProductIndex];
        if(existingProduct) {
            existingProduct.qty += 1;
        }
        else {
            cart.products.push({
                id,
                qty: 1
            });
        }
        cart.totalPrice += Number(price);
        console.log(cart);
        fs.writeFile(p, JSON.stringify(cart), error => {
            if(error) return console.error(error);
        });
    });
}

};

cart.js

const fs=require('fs')
const path=require('path')
module.exports = class Cart {

static addProduct(id, price) {
    const 
 p=path.join(path.dirname(process.mainModule.filename),
'data','cart.json')
    fs.readFile(p, (error, file) => {
        console.log('sgdf',id);
        let cart = {
            products: [],
            totalPrice: 0
        };
        if(!error) {
            console.log('insdie error')
            console.log(file)
            cart = JSON.parse(file)
        }
        console.log('outside error')

        const existingProductIndex = cart.products.findIndex(p => p.id 
  === id);
        console.log('dghjhjghfg',existingProductIndex)
        const existingProduct = cart.products[existingProductIndex];
        if(existingProduct) {
            existingProduct.qty += 1;
        }
        else {
            cart.products.push({
                id,
                qty: 1
            });
        }
        console.log('adsgfdgfh')
        cart.totalPrice += Number(price);
        console.log(cart);
        fs.writeFile(p, JSON.stringify(cart), error => {
            if(error) return console.error(error);
        });
    });
    }
   };

The error i am facing is

undefined:1



SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at /Users/ratnabhkumarrai/Desktop/max-project/models/cart.js:15:29
at FSReqCallback.readFileAfterClose [as onplete] 
(internal/fs/read_file_context.js:61:3)

In my Cart models when i try to console log and see i find that only my half of the code is executed the console log that i tried below does not get executed....What am i doing wrong here ?

Share Improve this question edited Oct 22, 2019 at 20:21 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Jun 20, 2019 at 17:16 RRR uzumakiRRR uzumaki 1,3284 gold badges28 silver badges63 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

I got this fixed by using writeFileSync instead of writeFile. I was trying to read a file that hadn't been closed yet

SyntaxError: Unexpected end of JSON input

Its usually caused by incorrect opening and closing of brackets or parenthesis, making the program expect more content even though the file ends before that. In you case this is caused by this line:

// cart.js 15th line
cart = JSON.parse(file);

Because the json loaded is incorrect. I would before parsing it, add a

console.log(file); 

to see what it is loading as a file and thereafter run it through https://jsonlint./ to check the json syntax.

Though as the error is in the first line, undefined 1, appears in the error you shared, it is possible that your file is empty

If you want there to be 0 products you must either habdle the case for empty or pass a valid json to your JSON.parse such as

// an empty array
[]
// an empty object
{}

本文标签: javascriptUnexpected end of JSON Input while parsing json file read asynchronouslyStack Overflow