관리 메뉴

필사(筆寫)

Nodejs ESM 모듈 동적 import 구문 몇가지 예시 본문

Service Developments/Node.js,Express

Nodejs ESM 모듈 동적 import 구문 몇가지 예시

코딩필사 2024. 7. 19. 18:07

1. DISK IO 잡아먹으면서 들어가는 방법

 

import { promises as fs } from 'fs';

import { pathToFileURL } from 'url';

 

const tempFilePath = './temp-bundle.mjs';

await fs.writeFile(tempFilePath, bundledCode);

const { default: Example } = await import(pathToFileURL(tempFilePath).href);

await fs.unlink(tempFilePath);

 

2. 메모리에 담고 처리하는 방법

import { createRequire } from 'module';

const require = createRequire(import.meta.url);

const { default: Component } = await import('data:text/javascript;base64,' + Buffer.from(bundledCode).toString('base64'));

 

쓴다면 후자가 낫다. 피차 express 전달할 때 메모리로 전달하기에..