5

I want data from the config.json file import to the index.js file in the same dir.

so I had it before

const {
prefix, token
} = require('./config.json');

now i would change the string so i need a json object, but how?

0

3 Answers 3

12
  1. In ES5 you can do it by

const object = require('./config.json');

The object will contain your JSON.

In ES6

import object from './config.json'
  1. Using fs module synchronously

const fs = require('fs')
const jsonData = JSON.parse(fs.readFileSync('config.json', 'utf-8'))
Sign up to request clarification or add additional context in comments.

1 Comment

Note: to import as json in ES6 "resolveJsonModule": true, must be set under compilerOptions in your tsconfig.json file.
1

Async example, if you're using ES6 modules:

import fs from 'fs/promises';

const {prefix, token} = JSON.parse(
  await fs.readFile('./config.json', 'utf-8')
);

See also:

Comments

-1

If you want the whole object, simply use:

const config = require('./config.json');

Otherwise if you want the contents of config.json, you can simply use the fs module to read the file. More specifically fs.readFileSync if you want it to be synchronous.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.