81

We're trying to use the new ways of exporting and importing 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+?

DarkLite1
  • 12,007
  • 34
  • 105
  • 185

5 Answers5

113

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
Idir Hamouch
  • 1,396
  • 1
  • 6
  • 13
34

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
  • 520
  • 6
  • 13
19

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)));
DevHub
  • 380
  • 3
  • 10
  • 2
    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
  • eslint throws error on this as the `await` keyword can only be used within `async` functions – Sina Nov 23 '21 at 12:59
-2

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
  • 507
  • 4
  • 10
-6

try to use

process.env.npm_package_version

this might help you

Osama Abdullah
  • 2,322
  • 2
  • 10
  • 19