Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import .json files in nodejs using ECMA Modules?

I am using nodejs 14.6.0. In my package.json file, I have type set to module.

type: module

Upon trying to do the following:

import serviceAccount from 'serviceAccount.json'

I get the following error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for C:\Users\Aditya\youtube-discord-bot\database\serviceAccount.json

Now, online it says that I must change my start script like so: node --experimental-json-modules index.js. However, even after having this, the same error occurs.

Is there a workaround to this? I want to require the serviceAccountKey using this functionality, as when trying to export it (as a .js file), Firebase gives me an error.

In the past, before doing this, I have simply been using require('./serviceAccount.json'), and this has worked fine. However, I want to switch to use these new ECMA modules.

like image 384
Rishab Jain Avatar asked May 02 '26 07:05

Rishab Jain


1 Answers

in case you need to use a .json file that you cannot alter and convert to an export, you can still use require as follows:

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const serviceAccount = require('./serviceAccount.json');
like image 63
JamesH Avatar answered May 03 '26 20:05

JamesH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!