I have learned NodeJS but I had some problems with _getProductsFromFile function in the Product class, I think the problem is static reserved word and the error i got was
TypeError: this._getProductsFromFile is not a function at Function.fetchAll (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/refactoring-MVC-pattern/models/product.js:57:10) at exports.getProduct (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/refactoring-MVC-pattern/controllers/products.js:20:11) at Layer.handle [as handle_request] (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/layer.js:95:5) at next (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/layer.js:95:5) at /Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/index.js:335:12) at next (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/index.js:275:10) at Function.handle (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/index.js:174:3)
Code in models/product.js
odule.exports = class Product {
constructor(title) {
this.title = title;
}
save() {
this._getProductsFromFile((products) => {
products.push(this);
fs.writeFile(
path.join(
path.dirname(process.mainModule.filename),
"data",
"products.json"
),
JSON.stringify(products),
(err) => {}
);
});
}
static fetchAll(cb) {
this._getProductsFromFile(cb);
}
_getProductsFromFile(cb) {
fs.readFile(
path.join(
path.dirname(process.mainModule.filename),
"data",
"products.json"
),
(err, fileContent) => {
if (err) cb([]);
else cb(JSON.parse(fileContent));
}
);
}
};
Code in controllers/products.js
const Product = require("../models/product");
exports.postAddProduct = (req, res, next) => {
const product = new Product(req.body.title);
product.save();
res.redirect("/");
};
exports.getProduct = (req, res, next) => {
Product.fetchAll((products) => {
res.render("shop", {
prods: products,
pageTitle: "Shop",
path: "/",
hasProducts: products.length > 0,
activeShop: true,
productCSS: true,
});
});
};
I need some help, please Thanks all.