0

So I was following a NodeJS tutorial.

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('db.json')
const db = low(adapter)

I tried using this:

import {default as lowdb} from 'lowdb'

This:

import lowdb from 'lowdb'

It all throws errors.

Am a bit confused on how to use it in the new way of import than the require which is depreciated.

Vpp Man
  • 2,384
  • 8
  • 43
  • 74
  • Check this out: https://www.geeksforgeeks.org/how-to-use-an-es6-import-in-node-js/ – Priyansh Agrawal Jun 27 '21 at 18:29
  • FWIW, require isn't deprecated. It's a part of the old syntax. ES6 is the new JS specification which has the new imports. Node doesn't support ES6 as of now (though it has experimental support). – Priyansh Agrawal Jun 27 '21 at 18:30
  • If you have other reasons to use `import`, fine, but `require` is not depreciated, deprecated, legacy, or anything like that. It has first-class support in Node.js and will for many years to come, probably until the end of Node.js itself. – Trott Jun 28 '21 at 02:13
  • 1
    @PriyanshAgrawal ESM is fully supported and stable in Node.js. It is not experimental support. – Trott Jun 28 '21 at 02:13
  • @Trott Ah! You're right. I've only used node12 and wasn't aware that they've marked modules as a stable feature in node13+. @OP, can you do a `node --version` and check if you're on a node version <=12 in which case you'll need to run node with the `--experimental-modules` flag. You can also refer to this answer - https://stackoverflow.com/a/39436580/5019181. – Priyansh Agrawal Jul 01 '21 at 16:39

1 Answers1

1

There is one thing to change and a second thing to check if that first one doesn't quite solve it.

  1. The module does not have a default export, and the two import statements you tried assume there is a default export. Follow along with the usage example in the package page, which includes import { Low, JSONFile } from 'lowdb'. Using that and/or other things listed in the API at the package page should get you what you need.

  2. If you do that and it still doesn't work, be sure that you have either named your file .mjs or else included "type": "module" in your package.json. See the Node.js documentation for packages for more information. (This will work for all Node.js versions supported as of this writing, which would be Node.js versions 12.x, 14.x, and 16.x. If you are running 10.x or earlier, you will need to upgrade.)

Trott
  • 66,479
  • 23
  • 173
  • 212