부트캠프
webSocket_Project_2
한우종
2024. 10. 2. 23:04
public에서 assets파일 불러오는 방법
클라이언트에서 assets에 있는 데이터를 불러와 비교를 해줘야하는데 현재 구조에서는 assets파일이 가장 상위폴더에 위치해 있기때문에 정적파일인 public에서는 읽어올수없는 문제가 발생했다.
이를 해결하기 위한 방법으로는 여러가지가 있다고 하는데 나는 assets의 파일을 public안에 넣어주어 그 안에서 호출하는 방법을 사용했다.
위 사진처럼 assets파일을 public파일 안에 넣어주고 그냥 import 하면 될주 알았으나
json파일은 일반적인 방법으로는 import를 사용할 수 없다고한다.
json파일을 import하려면 with문에 타입을 json으로 설정하면 아래와 같이 import할 수 있게된다.
import { sendEvent } from "./Socket.js";
import stages from "./assets/stage.json" with { type: "json" };
import itemUnlock from "./assets/item_unlock.json" with { type: "json" };
import items from "./assets/item.json" with { type: "json" };
class Score {
score = 0;
HIGH_SCORE_KEY = "highScore";
stageChange = true;
stageIndex = 0;
constructor(ctx, scaleRatio) {
this.ctx = ctx;
this.canvas = ctx.canvas;
this.scaleRatio = scaleRatio;
}
update(deltaTime) {
this.score += (deltaTime + stages.data[this.stageIndex].scorePerSecond) * 0.01;
if (Math.floor(this.score) % 100 === 0 && this.stageChange) {
this.stageChange = false;
console.log("현재 스테이지:", stages.data[this.stageIndex].id);
if (this.stageIndex + 1 < stages.data.length) {
sendEvent(11, {
currentStage: stages.data[this.stageIndex].id,
targetStage: stages.data[this.stageIndex + 1].id,
clientScore: this.score,
});
stage.json의 값을 가져오기위해 stages라는 이름으로import하면 stages.<??>.<??> ??안에 갸져올 데이터를 입력하면 가져온다.
마지막으로 서버쪽에서도 파일을 읽어올수 있도록 경로를 수정해줘야함
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
let gameAssets = {}; //전역변수 여기에 json파일값을 받아옴
const __filename = fileURLToPath(import.meta.url);
// path.dirname() 함수는 파일 경로에서 디렉토리 경로만 추출 (파일 이름을 제외한 디렉토리의 전체 경로)
const __dirname = path.dirname(__filename);
!!!!!!!!!!!!!!!!!!!!!!!!여기!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
const basePath = path.join(__dirname, "../../public/assets");
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//파일 읽는 함수
//비동기 병렬 비동기 파일을 병렬로 동시에 처리한다.
const readFileAsync = (filename) => {
return new Promise((resolve, reject) => {
fs.readFile(path.join(basePath, filename), "utf8", (err, data) => {
if (err) {
reject(err);
return;
}
resolve(JSON.parse(data));
});
});
};
//Promise.all
export const loadGameAssets = async () => {
try {
const [stages, items, itemUnlock] = await Promise.all([
readFileAsync("stage.json"),
readFileAsync("item.json"),
readFileAsync("item_unlock.json"),
]);
gameAssets = { stages, items, itemUnlock };
return gameAssets;
} catch (err) {
throw new Error("assets파일 에러" + err.message);
}
};
export const getGameAssets = () => {
return gameAssets;
};