Import '.json' extension in ES6 Node.js throws an error

Javascriptnode.jsEs6 Modules

Javascript Problem Overview


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+?

Javascript Solutions


Solution 1 - Javascript

> > > 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

Solution 2 - Javascript

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

Solution 3 - Javascript

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)));

Solution 4 - Javascript

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.

Solution 5 - Javascript

try to use

process.env.npm_package_version

this might help you

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDarkLite1View Question on Stackoverflow
Solution 1 - JavascriptIdir HamouchView Answer on Stackoverflow
Solution 2 - JavascriptCarter CobbView Answer on Stackoverflow
Solution 3 - JavascriptDevHubView Answer on Stackoverflow
Solution 4 - JavascriptAnuj ShahView Answer on Stackoverflow
Solution 5 - JavascriptAhmed KhattabView Answer on Stackoverflow