简体   繁体   English

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

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

I'm reading the book introducing NodeJS with a simple web application example.我正在阅读介绍 NodeJS 的书,其中包含一个简单的 web 应用程序示例。 The requirement in the example is that there are several data store classes in its own module, and we need to adopt the data store dynamically by setting environment variable.示例中的要求是在自己的模块中有多个数据存储类,我们需要通过设置环境变量来动态采用数据存储。 The code snippets of the example is something like following:该示例的代码片段如下所示:

// 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);
});

The code snippets above is not same as the one in the book overall.上面的代码片段与本书中的代码片段不同。 But the concept is same.但是概念是一样的。 It works fine in my local environment, but I'm wondering isn't there any problem if the request is coming and handled before the data store is imported due that the import function is async operation?它在我的本地环境中运行良好,但我想知道如果由于导入 function 是异步操作而在导入数据存储之前收到并处理了请求是否有任何问题? Are there other solutions which can fulfill the requirement?是否有其他解决方案可以满足要求? Or I'm just missing something that the example from the book is just masterpiece?或者我只是错过了书中的例子只是杰作的东西? Thanks in advance!提前致谢!

If you want to guarantee that store has been initialized before any requests are handled by your express app, you could set up the express listener after the load promise has resolved.如果您想保证在您的 express 应用程序处理任何请求之前已初始化store ,您可以在load promise 解决后设置 express listener器。 This would be as simple as the following:这很简单,如下所示:

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