Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 解析异步读取的JSON文件时JSON输入意外结束_Javascript_Node.js - Fatal编程技术网

Javascript 解析异步读取的JSON文件时JSON输入意外结束

Javascript 解析异步读取的JSON文件时JSON输入意外结束,javascript,node.js,Javascript,Node.js,我是NodeJS新手,在我的项目中使用MVC模式,所以当我试图将产品添加到cart.json文件时,我面临着这个问题 routes file const Product = require('../models/product'); const Cart = require('../models/cart') exports.postcart = (req,res,next) => { const proid = req.params.productcartid Pro

我是NodeJS新手,在我的项目中使用MVC模式,所以当我试图将产品添加到cart.json文件时,我面临着这个问题

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)
    })
}
产品模型

  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)   
               })
          })
      } 
  }
推车模型

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);
        });
    });
    }
   };
我面临的错误是

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 oncomplete] 
(internal/fs/read_file_context.js:61:3)
未定义:1
SyntaxError:JSON输入意外结束
在JSON.parse()处
at/Users/ratnabhkumarrai/Desktop/max project/models/cart.js:15:29
在FSReqCallback.readFileAfterClose[作为oncomplete]
(内部/fs/read_file_context.js:61:3)
在我的购物车模型中,当我尝试控制台日志时,我发现只有我的一半代码被执行,我在下面尝试的控制台日志没有被执行……我在这里做错了什么

SyntaxError: Unexpected end of JSON input
这通常是由于括号或圆括号的不正确打开和关闭导致的,这使得程序需要更多的内容,即使文件在此之前结束。 在您的情况下,这是由以下行引起的:

// cart.js 15th line
cart = JSON.parse(file);
因为加载的json不正确。在解析它之前,我会添加一个

console.log(file); 
查看它作为文件加载的内容,然后运行它以检查json语法

虽然错误出现在第一行,undefined 1出现在您共享的错误中,但您的文件可能是空的

如果您希望有0个产品,则必须将其包装为空,或者将有效的json传递给您的json.parse,例如

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

我通过使用writeFileSync而不是writeFile解决了这个问题。我试图读取一个尚未关闭的文件

嗯,我复制粘贴了讲师的代码,但仍然存在问题。唯一不同的是,我尝试在我的路线文件中使用承诺,而他使用了回调,所以问题在我的路线文件中,我猜,但仍然没有答案,因为问题就在那里,正如我的回答所说,可能是这样空的更新请看一看!嘿,伙计,就是这样,空字符串不是有效的json,空数组可以处理这个案例,也可以修改json。