node version: v13.14.0 and npm version:6.14.4
I tried to run this code with the latest as well as the previous builds of node but it didn't work out.
This is what I got after running npm start:
$ npm start
> 1st-app@1.0.0 start D:\web development\node\1st app
> nodemon app.js
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
internal/validators.js:121
throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined
at validateString (internal/validators.js:121:11)
at Object.dirname (path.js:583:5)
at Object.<anonymous> (D:\web development\node\1st app\models\cart.js:5:10)
at Module._compile (internal/modules/cjs/loader.js:1118:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1138:10)
at Module.load (internal/modules/cjs/loader.js:982:32)
at Function.Module._load (internal/modules/cjs/loader.js:875:14)
at Module.require (internal/modules/cjs/loader.js:1022:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (D:\web development\node\1st app\controllers\shop.js:2:14) {
code: 'ERR_INVALID_ARG_TYPE'
}
[nodemon] app crashed - waiting for file changes before starting...
Here is my cart.js 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) {
//Fetch the previous cart
fs.readFile(p, (err, fileContent) => {
let cart = { products: [], totalPrice: 0 };
if (!err) {
cart = JSON.parse(fileContent);
}
//Analyse the cart => Find existing product
const existingProductIndex = cart.products.findIndex(
(prod) => prod.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);
});
});
}
};
This is my shop.js code:
const Product = require("../models/product");
const Cart = require("../models/cart");
exports.getCart = (req, res, next) => {
res.render("shop/cart", {
pageTitle: "Your Cart",
path: "/cart",
});
};
exports.postCart = (req, res, next) => {
const prodId = req.body.productId;
Product.findById(prodId, (product) => {
Cart.addProduct(prodId, product.price);
});
res.redirect("/cart");
};
I tried everything which I could but this error is not resolved and I am stuck here.
Any help will be great.
Thank You in advance.