繁体   English   中英

如何导出使用 NodeJS 中的 ES6 模块动态导入的 class 的实例?

[英]How to export the instance of the class which is imported dynamically with ES6 module in NodeJS?

我正在阅读介绍 NodeJS 的书,其中包含一个简单的 web 应用程序示例。 示例中的要求是在自己的模块中有多个数据存储类,我们需要通过设置环境变量来动态采用数据存储。 该示例的代码片段如下所示:

// memory-store.mjs
// The data store for storing data in memory

export default class MemoryStore {
  // Some CRUD operation
}
// fs-store.mjs
// The data store for storing data into file system

export default class FSStore {
    // Some CRUD operation
}
// store.mjs
// Provide a async function to import data store dynamically and
// set the instance to variable store, which is exported

let store;

async function load() {
    try {
        const moduleName = process.env.MODULE_NAME ?? 'memory';
        const storeModule = await import(`./${moduleName}-store.mjs`);
        const storeClass = storeModule.default;
        store = new storeClass();
        return store;
    } catch(err) {
        throw new Error('Something goes wrong...');
    }
}

export { load, store };
// app.mjs
// Import the function to load the data store dynamically and
// the exported store for fetching data list

import express from 'express';
import { load, store } from './store.mjs';

const app = express();

load()
.then(store => {})
.catch(err => console.error(`Exception with error: ${err}`));

app.use('/', (req, res, next) => {
    const dataList = store.retrieveAll();
    res.send(dataList);
});

上面的代码片段与本书中的代码片段不同。 但是概念是一样的。 它在我的本地环境中运行良好,但我想知道如果由于导入 function 是异步操作而在导入数据存储之前收到并处理了请求是否有任何问题? 是否有其他解决方案可以满足要求? 或者我只是错过了书中的例子只是杰作的东西? 提前致谢!

如果您想保证在您的 express 应用程序处理任何请求之前已初始化store ,您可以在load promise 解决后设置 express listener器。 这很简单,如下所示:

import express from 'express';
import { load, store } from './store.mjs';

const app = express();

app.use('/', (req, res, next) => {
    const dataList = store.retrieveAll();
    res.send(dataList);
});

load()
.then(() => {
   app.listen(port, () => {
     console.log(`Example app listening at http://localhost:${port}`);
   });
})
.catch(err => console.error(`Exception with error: ${err}`));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM