31

We're trying to use the new ways of exporting and imported modules for ES6 with Node.js. It's important for us to get the version number from the package.json file. The following code should do that:

import {name, version} from '../../package.json'

However, on execution the following error is thrown: ^

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for T:\ICP\package.json imported from T:\ICP\src\controllers\about.js

Is there something we're missing?
Is the extension .json not supported?
Is there another way to retrieve this information using Node.js 13+?

Mike B.
  • 10,955
  • 19
  • 76
  • 118
DarkLite1
  • 9,743
  • 30
  • 88
  • 160

5 Answers5

52

According to the Node.js ES Modules docs --experimental-json-modules. is required for importing JSON files.

Include the --experimental-json-modules flag for the module to work.

node --experimental-json-modules about.js
Community
  • 1
  • 1
Idir Hamouch
  • 693
  • 4
  • 9
4

You can use it as in docs node-js as follow:

import { readFile } from 'fs/promises';

const json = JSON.parse(await readFile(new URL('../../package.json', import.meta.url)));
Mustafa Agha
  • 78
  • 1
  • 5
  • 1
    If you're doing this on a server... I highly recommend the cleaner `fs-extra`, which promises everything transparently and supports recursive directory copy – Ray Foss May 07 '21 at 18:10
2

You can sill import require in an ES6 module for Node.js:

import { createRequire } from "module"; // Bring in the ability to create the 'require' method
const require = createRequire(import.meta.url); // construct the require method
const my_json_file = require("path/to/json/your-json-file.json") // use the require method
Carter Cobb
  • 181
  • 2
  • 11
-1

try to use

process.env.npm_package_version

this might help you

Ahmed Khattab
  • 1,790
  • 2
  • 6
  • 17
-1

yes, there is another way to fetch version, but it is without ES6 module system. Here's a working example: https://codesandbox.io/s/funny-banzai-2xgvf.

Anuj Shah
  • 397
  • 3
  • 9