點燈坊

失くすものさえない今が強くなるチャンスよ

Reading JSON File in Node

Sam Xiao's Avatar 2022-11-15

We often use JSON files to store configuration. For example, hostportloginpassword and database settings for the database server. Since Node supports ES module, we can just use import statement to import JSON files synchronously.

Version

Node 16.18.0

Node Configuration

package.json

{
  "type": "module",
  "name": "express-lab",
  "version": "1.0.0",
  "scripts": {
    "dev": "nodemon app.js"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.20",
    "prettier": "^2.7.1"
  }
}

Line 2

"type": "module"
  • Use ES module by default for Node.

JSON File

config.json

{
  "host": "mssql-2017",
  "port": 1433,
  "user": "sa",
  "password": "111111",
  "database": "psi"
}

JSON file for configuration.

ES Module

app.js

import config from './config.json' assert { type: 'json' }

console.log('typeof config: ', typeof config)
console.log('config', config)
  • Use import statement to import the JSON file
  • Assert the file format is JSON type
  • JSON file is read as Object type

config000

Conclusion

  • Since import statement read JSON file synchronously, we don’t have to use other function or package to read JSON file asynchronously