Using ESM with legacy CommonJS modules in NodeJS

I have been a full-time Javascript programmer since 2010. I have an elaborate library of utilities and snippets and patterns and practices based on CommonJS running in NodeJS. I have absolutely no use for ESM. I understand its benefit in some situations but, none of them are ones I am in. Consequently, I am unfamiliar with it.


So, when I found that, as I implement a new app, that OpenAI has made it's new, V4, npm module entirely incompatible with my previous CommonJS library, I was annoyed that I could not just pick up previous code. When I found that it is only published as ESM and that you can't just put "import openAi from openai"  inline with require(), I was furious.

Trying to figure out how to use ESM in a CJS world, I have read so many idiots saying, "Don't. ESM is great. Rewrite your code base to be cool and modern." Or, convoluted crap that tells you how to do some complicated thing related to this topic. I have to tell you that my last couple of hours have been an epic fail in Google, StackOverflow and everyone else.

It made me so mad that I was forced to the final resort: RTFM. In this case, the NodeJS module documentation.

I'm sure you have as little interest in reading about ESM as I do, so ere is the answer:

I wrote an interface module. All it does is use the NodeJS import() function with its promise. (You can obviously use this without the structure but I personally prefer callbacks to async/await and think this is easier to interpret.)

This module only import()'s and is called mport-openai.js:

'use strict';
module.exports = async function(callback) {
    const openAi = await import('openai');
    callback('', openAi);
};

This is in my main program:

require('./import-openai')((err, openAi)=>{
    //do cool stuff here
});

I make no claim that this is brilliant insight. In fact, I know it is totally obvious... Once you know about it,which you won't until you do and Google was no help until you got here.

You're welcome.

ps, You might have thought, "Why'd he have to tell me this whole long story about legacy CommonJS, ESM, node modules, looking for import(), etc?" The answer is Google Bait, not that I think you actually care about my journey. It needs the explanation for the index.