javaScript/nodeJs

require.context / 파일경로 가져오기.

부엉이사장 2023. 3. 8. 21:23

이미지파일을 디렉토리별로 분류해서 관리한다.

js파일에서 특정디렉토리에 어떤 파일들이 있는지 동적으로 알고싶은데

node처럼 path모듈을 사용할수도 없고..해서 찾아봤더니 require.context가 있더라

 

 

    const context = require.context("../assets/img", false, /\.png$/);
    for (const key of context.keys()) {
      console.log(key);
    }

참고로 assets/img폴더안에 있는 이미지들을 가져올거다.

 

require.context메서드 파라미터는 각각 

첫번째 : 찾을 경로

두번째 : 불린값인데 하위 폴더까지 다가져올거냐 마냐임.

세번째 : 원하는 파일명 정규식

 

 

결과를 보면

./1.png
./2.png
./3.png

이렇게 나온다.

'javaScript > nodeJs' 카테고리의 다른 글

websocket  (0) 2024.11.09
production// 배포모드  (0) 2023.01.16
배포시 모듈정리/  (0) 2022.12.07
nodejs // dotenv 사용  (0) 2022.09.24
다른파일로 관리 require//nodejs(js import아님)  (0) 2022.08.06