Hi, i’m follow a course about Node and the teacher create this code
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) {
fs.readFile(p, (err, fileContent) => {
let cart = { products: [], totalPrice: 0 };
if (!err) {
cart = JSON.parse(fileContent);
}
const existingProductIndex = cart.products.findIndex(prod => prod.id === id);
const existingProduct = cart.products[existingProductIndex];
let updatedProduct;
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);
});
});
}
};
the problem, for him work everything and don’t get any error on me i get this:
const existingProductIndex = cart.products.findIndex(prod => prod.id === id);
^
TypeError: Cannot read property 'findIndex' of undefined
at fs.readFile (C:\Users\gioff\Desktop\Courses\Max\Project-express\models\cart.js:18:50)
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:54:3)
why?