javascriptnode.jsparsingfsini

Parse INI file in Node.js


I build a Node.js tool in order to change GCP config quickly. But I'm a bit stuck on the parsing of the config_nameOfConfig file. It looks like this :

[core]
account = email@example.fr
project = project-example
disable_usage_reporting = False

[compute]
region = europe-west1-b

(This file is available in '/Users/nameOfUser/.config/gcloud')

And I want to convert it in an object like this :

const config = {
  account:"email@example.fr",
  project:"project-example",
  disable_usage_reporting:false,
  region:"europe-west1-b",
};

I get the content of this file with the fs.readFileSync function who converts it into a string.

An idea ?


Solution

  • This seems to be an ini file format. Unless you want to do the parsing yourself, you'd better just download a library to your project, for example:

    npm install ini
    

    Then in the code:

    var ini = require('ini')
    var fs = require('fs')
    var config = ini.parse(fs.readFileSync('./config_nameOfConfig', 'utf-8'))
    

    In config you should now have object containing the data in the file. You can console.log(config) to see how it exactly looks like.