const fs = require("fs"); // 파일 시스템 모듈
const path = require("path"); // OS 운영체제 파일 경로 통합 모듈
const products = [];
module.exports = class Product {
// 생성자 : 모든 class에는 constructor가 꼭 있어야함.
// 이것은 생성자 함수를 만들 때, 필요한 매개변수를 정의하는 곳과 같다고 생각하면 된다.
// constructor : new 키워드로 객체를 생성할 때 호출되는 함수임.
// ex : function Product(name, title) { console.log(name, title)}
constructor(t) {
this.title = t;
}
save() {
// products.push(this);
const p = path.join(
path.dirname(require.main.filename),
"data",
"products.json"
);
fs.readFile(p, (err, fileContent) => {
const products = [];
if (!err) { // ❌ 에러 발생 지점
products = JSON.parse(fileContent);
console.log("products : ", products);
}
products.push(this);
fs.writeFile(p, JSON.stringify(products), (err) => {
console.log("err : ", err);
});
});
}
static fetchAll() {
return products;
}
};
products = JSON.parse(fileContent);
^
TypeError: Assignment to constant variable.
save()
인스턴스 함수에서 선언한 const products = [];
가 에러 원인이었음.
JSON.parse()
함수가 실행될 때, 나는 아래와 같은 생각을 했다.
객체(배열)을 재구성하겠지?
const
키워드로 변수 선언해도 상관없겠지?
해당 생각이 잘 못 되었다.
JSON.parse()
함수가 내부에서 실행될 때, 새롭게 변수를 재정의하기 때문에 에러가 발생하는 것이었다.
즉, 객체(배열)을 재구성하는 것이 아니라, 변수 자체를 재정의하기 때문에
TypeError: Assignment to constant variable
에러가 출력되었던 것임.
const 키워드로 선언된 변수는 한 번 할당되면 재할당 할 수 없기 때문이다.
save() {
// products.push(this);
const p = path.join(
path.dirname(require.main.filename),
"data",
"products.json"
);
fs.readFile(p, (err, fileContent) => {
// ❌ const products = [];
let products = [];
if (!err) {
products = JSON.parse(fileContent);
console.log("products : ", products);
}
products.push(this);
fs.writeFile(p, JSON.stringify(products), (err) => {
console.log("err : ", err);
});
});
}