-
ESModule 로 express 작성하기백엔드/express.js 2024. 5. 17. 16:51728x90
{ "name": "webrtc", "version": "1.0.0", "description": "", "main": "server.mjs", // 확장자 변경 "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "nodemon ./src/server.mjs" // 명령어 작성 }, "author": "", "license": "ISC", "dependencies": { "express.js": "^1.0.0", "pug": "^3.0.2" }, "type": "module" // 추가 }
ESModule 을 사용하기 위해서는 "type": "module" 을 설정해야 한다. 또한, 파일의 확장자는 mjs 로 변경해야 한다.
import express from 'express'; import { fileURLToPath } from "url"; // 👈 추가 const app = express() console.log("결과값: ", fileURLToPath(new URL(".", import.meta.url))) const __dirname = fileURLToPath(new URL(".", import.meta.url)); // 👈 추가 app.set('view engine', 'pug') app.set("views", __dirname + 'views') const handleListen = () => console.log(`Listening on http:`) app.listen(3000,handleListen)
server.mjs 파일은 위와 같이 작성한다. 여기서 __dirname 은 ESModule 에는 존재하지 않으므로 fileURLToPath 와 import.meta.url 을 이용하여 만들어줘야 한다.
file:///E:/(%EB%94%94%EC%A7%80%ED%84%B8%EC%BB%A8%EB%B2%84%EC%A0%84%EC%8A%A4)%20React%20%EB%B0%98%20(12.28)/%EC%B5%9C%EC%86%8C%EC%97%B0/webRtc/src/server.mjs
import.meta.url 은 파일경로이다.
new URL() 반환값 new URL() 의 반환값은 위와 같다. href 에 파일명을 제외한 파일의 전체경로가 표시된다.
console.log("결과값: ", fileURLToPath(new URL(".", import.meta.url)))
__dirname 을 출력해보면 아래와 같다.
결과값: E:\(디지털컨버전스) React 반 (12.28)\최소연\webRtc\src\
결국 파일이 위치한 디렉토리 경로이다.
728x90'백엔드 > express.js' 카테고리의 다른 글
조건쿼리 (conditional query) (0) 2024.05.20 이미지 업로드 - multer (0) 2024.05.16 노드 cors 에러 해결하기 - Error: unable to verify the first certificate (0) 2024.05.16 express 문서 - 미들웨어 코드 (0) 2024.04.15 express 프레임워크 기본이론 (0) 2021.10.12