ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • ESModule 로 express 작성하기
    백엔드/express.js 2024. 5. 17. 16:51
    728x90
    {
      "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
Designed by Tistory.