Javascript TypeError:无法读取属性';findIndex';nodeJS中未定义的

Javascript TypeError:无法读取属性';findIndex';nodeJS中未定义的,javascript,arrays,node.js,Javascript,Arrays,Node.js,这是我的代码: const path = require('path'); const fs = require('fs'); let cart = { products: [], totalPrice: 0}; let jsonFilePath = path.join(path.dirname(process.mainModule.filename), 'data', 'cart.json' ); module.exports = class Cart { static addPro

这是我的代码:

const path = require('path');
const fs = require('fs');
let cart = { products: [], totalPrice: 0};
let jsonFilePath = path.join(path.dirname(process.mainModule.filename),
'data',
'cart.json'
);

module.exports = class Cart {
    static addProductToCart( productId, productPrice) {
        fs.readFile(jsonFilePath, (err, cartData) => {
            if(err){
                console.error(err);
            } else {
                cart = JSON.parse(cartData);
            }   
                const existingProductIndex = cart.products.findIndex(product => product.id === productId );

我在最后一行中出错了,我不知道为什么。请帮助,提前谢谢。

在您遇到错误的代码行之前控制台cart.products请共享cart json和您从程序中获得的输出感谢您的帮助@Deep Kakkar,感谢您关心帮助我,但我找到了解决方案我使用的是[]而不是{}由于此购物车,未提取产品。再一次感谢。总之,如果答案中包含了对代码意图的解释,以及为什么在不介绍其他代码的情况下解决了问题,那么答案会更有帮助。
const fs=require('fs');
const path = require('path');
const p = path.join(path.dirname(process.mainModule.filename), 'data', 'cart.json');

module.exports=class Cart{
    static addProduct(id,productPrice){
        //Fetch the previous cart
        fs.readFile(p,(err,fileContent)=>{
            let cart={products:[],totalPrice:0};
                if(!err)
                {
                    cart=JSON.parse(fileContent);
                }
                //Analyze the cart=>Find Existing Product
                const existingProductIndex=cart.products.findIndex(x=>x.id===id);
                const existingProduct = cart.products[existingProductIndex];
                let updatedProduct;
                //Add New Product/increase Quantity
                if (existingProduct)
                {
                    updatedProduct={...existingProduct};
                    updatedProduct.qty = updatedProduct.qty+1;
                    cart.products={...cart.products};
                    cart.products[existingProductIndex]=updatedProduct;
                }
                else{
                    updatedProduct={id:id,qty:1};
                    cart.products = [...cart.products,updatedProduct];
                }
                cart.totalPrice = cart.totalPrice+ +productPrice;
                fs.writeFile(p, JSON.stringify(cart),(err)=>{
                    console.log(err);
                });
        });
    }
}