DEV Community

Cover image for How to import node-persist into a Node.js ES6 project
Juha
Juha

Posted on

How to import node-persist into a Node.js ES6 project

Working on a Node.js project with ES6 syntax can sometimes present challenges, especially when incorporating modules like node-persist that aren't natively aligned with the ES6 import style.

Fortunately, there's a workaround to use CommonJS modules within ES6 scripts, and here's how you can apply it to node-persist.

const nodePersist = await import('node-persist');

const storage = nodePersist.default.create();
await storage.init({ dir: 'my-path' });

const foo = await storage.getItem('foobar');
Enter fullscreen mode Exit fullscreen mode

Key Takeaways:

  • Dynamic import() function: This approach utilizes the dynamic import() function, which is essential for loading CommonJS modules in an ES6 environment.

  • The default property: After importing, it's crucial to access the default property. This is where the module's main functionality resides. Hence, nodePersist.default.create() is used to create a new instance.

Understanding the differences is key: CommonJS modules (require()) represent the traditional standard in Node.js, while ES6 modules (import) offer a more modern approach.

Bridging these two with dynamic import ensures that your project can leverage the best of both worlds.

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay