How to use the parse function from ini

Find comprehensive JavaScript ini.parse code examples handpicked from public code repositorys.

ini.parse is a function that parses a string of INI configuration data into a JavaScript object.

91
92
93
94
95
96
97
98
99
100
      " Remove all rights from everyone else but owner"
  );
}

var content = fs.readFileSync(filename, "utf-8");
var config = ini.parse(content);

if (!config.maxctrl) {
  throw Error("Error: " + filename + " does not have a [maxctrl] section");
}
fork icon330
star icon0
watch icon133

20
21
22
23
24
25
26
27
28
29
30


// Read in the config file to get the parameters. If the parameters are not set
// or the file does not exist, we exit this program.
try {
    var config_file = fs.readFileSync(config_file, 'utf-8');
    var config = ini.parse(config_file);
    if (config.appID == undefined || config.appID == '') {
        throw new Exception('no settings');
    }
    if (config.accessKey == undefined || config.accessKey == '') {
fork icon8
star icon20
watch icon15

How does ini.parse work?

ini.parse is a function provided by the ini package in Node.js that takes a string of INI configuration data as input and returns a JavaScript object representing the parsed configuration.

The INI format is a simple way of representing key-value pairs in a text file, where each section of the file is denoted by a header in square brackets and subsequent lines are key-value pairs in the format key=value.

ini.parse works by splitting the input string into lines, and then iterating over each line and processing it depending on whether it represents a header or a key-value pair. If the line represents a header, the function creates a new object with an empty property whose name matches the header name. If the line represents a key-value pair, the function adds the key-value pair as a property to the most recently created object.

When ini.parse has processed all the lines of the input string, it returns the final object representing the parsed configuration.

The ini.parse function can also accept an optional second argument that specifies parsing options, such as the character used to delimit key-value pairs and whether to allow duplicate keys.

1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
g_test = false;

console.log( "Reading configuration from file", process.argv[2] );

try{
    var config = ini.parse(fs.readFileSync(process.argv[2],'utf-8'));
    if ( config.server ){
        g_host = config.server.host || g_host;
        g_port = config.server.port || g_port;
        if ( config.server.tls == "0" || config.server.tls == "false" ){
fork icon6
star icon12
watch icon6

7
8
9
10
11
12
13
14
15
16
17
18
const ffi = require('ffi-napi');
const clipboardy = require('clipboardy');
const { Console } = require("console");
var fsR = require('fs-reverse'), filePath = process.env.LOCALAPPDATA + '\\SCUM\\Saved\\Logs\\SCUM.log';


const config = ini.parse(fs.readFileSync('./config.ini', 'utf-8'));


// create the server
let server = net.createServer(connection => {
    // run all of this when a client connects
fork icon1
star icon3
watch icon3

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const ini = require("ini");

const configData = `
[server]
port = 3000
host = localhost

[database]
username = root
password = mypass
`;

const config = ini.parse(configData);

console.log(config.server.host); // Output: localhost
console.log(config.database.password); // Output: mypass

In this example, the configData variable contains an INI configuration string with two sections: server and database. The ini.parse function is used to parse this string into a JavaScript object, which is assigned to the config variable. The console.log statements demonstrate how to access the values of the parsed configuration using dot notation to access the properties of the config object.

11
12
13
14
15
16
17
18
19
20
21
run();


function getNamedProfiles() {
  let namedProfiles;
  if (fs.existsSync(configFilePath)) {
    const config = ini.parse(fs.readFileSync(configFilePath, "utf-8"));
    namedProfiles = {};
    Object.keys(config).forEach((key) => {
      const profileName = key.replace("profile", "").trim();
      if (!namedProfiles[profileName]) {
fork icon1
star icon2
watch icon1

5
6
7
8
9
10
11
12
13
14
15
16
17


const isWindows = process.platform === 'win32';


const readRc = filePath => {
	try {
		return ini.parse(fs.readFileSync(filePath, 'utf8')).prefix;
	} catch {}
};


const getEnvNpmPrefix = () => {
fork icon0
star icon3
watch icon1

8
9
10
11
12
13
14
15
16
17
let value = RED.util.getMessageProperty(msg, node.property);
if (value !== undefined) {
	if (typeof value === 'string') {
		try {
			// Object.assign() to avoid bugs due to Object.create(null) used by the ini library
			value = Object.assign({}, ini.parse(value));
			RED.util.setMessageProperty(msg, node.property, value);
			node.send(msg);
		} catch (e) {
			node.error(e.message, msg);
fork icon0
star icon3
watch icon4

210
211
212
213
214
215
216
217
218
219
let npmConfig = {}
for (const loc of possibleRcPaths) {
  if (fs.existsSync(loc)) {
    try {
      // the closer config file (the one with lower index) takes higher precedence
      npmConfig = Object.assign({}, ini.parse(fs.readFileSync(loc, 'utf-8')), npmConfig)
    } catch (e) {
      // in case of file permission issues, etc.
    }
  }
fork icon0
star icon1
watch icon1

83
84
85
86
87
88
89
90
91
92
93
mLog("Generating invocation parameters");
var inputMessage = "A".repeat(testRecord.input.parameter_size);
var params = {sleep: testRecord.input.delay, message: inputMessage};


mLog("Loading wskprops");
const config = ini.parse(fs.readFileSync(testRecord.input.config_file, "utf-8"));
mLog("APIHOST = " + config.APIHOST);
mLog("AUTH = " + config.AUTH);
mLog("-----\n");
const wskParams = `--apihost ${config.APIHOST} --auth ${config.AUTH} -i`;    // to be used when invoking setup and teardown via external wsk
fork icon1
star icon0
watch icon2

18
19
20
21
22
23
24
25
26
27
28
// Check if a config file was provided, if so, load that config, if not, use the default config file
if (process.argv[2] == undefined) {
    config = ini.parse(fs.readFileSync('./config.ini','utf-8'))
}
else {
    config = ini.parse(fs.readFileSync(process.argv[2],'utf-8'))
}


const wsPort = config.ServerConfig.NodeCommunicationPort;
const apiPort = config.ServerConfig.APIPort;
fork icon1
star icon0
watch icon2

10
11
12
13
14
15
16
17
18
19
20
run();


function getNamedProfiles() {
  let namedProfiles;
  if (fs.existsSync(configFilePath)) {
    const config = ini.parse(fs.readFileSync(configFilePath, 'utf-8'));
    namedProfiles = {};
    Object.keys(config).forEach((key) => {
      const profileName = key.replace('profile', '').trim();
      if (!namedProfiles[profileName]) {
fork icon1
star icon0
watch icon1

67
68
69
70
71
72
73
74
75
76
77
78
  } catch (err) { /* do nothing */ }
}


function tryConfigPath(configPath) {
  try {
    return ini.parse(fs.readFileSync(configPath, 'utf-8')).prefix;
  } catch (err) { /* do nothing */ }
}


/**
fork icon0
star icon3
watch icon1

10
11
12
13
14
15
16
17
18
19
20
21
22
  //can't just try and parse it and let it throw if it's not ini.
  //everything is ini. even json with a syntax error.


  if(/^\s*{/.test(content))
    return JSON.parse(stripJsonComments(content))
  return ini.parse(content)


}


var file = exports.file = function () {
fork icon31
star icon0
watch icon15

22
23
24
25
26
27
28
29
30
31
  return;
}

const avdPath = environment.getAvdDir(avdName);
const configFile = path.join(avdPath, 'config.ini');
const config = ini.parse(fs.readFileSync(configFile, 'utf-8'));

if (!config['skin.name']) {
  const width = config['hw.lcd.width'];
  const height = config['hw.lcd.height'];
fork icon0
star icon0
watch icon2

+ 6 other calls in file

14
15
16
17
18
19
20
21
22
23
24
const booleanKeys = ['raw_html', 'show_images'];


const getDataFromIniFile = () => {
    const iniFileContents = `${fs.readFileSync(pathToIniFile)}`;
    console.log(iniFileContents);
    const json = ini.parse(iniFileContents);
    const cleanJson = {};
    Object.keys(json).forEach(key => {
        cleanJson[key] = json[key].value;
        if(booleanKeys.includes(key)){
fork icon0
star icon0
watch icon1

146
147
148
149
150
151
152
153
154
155
156
157
158
  await sandbox.run('config', ['delete', 'access'], { home })


  t.equal(sandbox.config.get('access'), null, 'acces should be defaulted')


  const contents = await fs.readFile(join(home, '.npmrc'), { encoding: 'utf8' })
  const rc = ini.parse(contents)
  t.not(rc.access, 'access is not set')
})


t.test('config delete multiple keys', async t => {
fork icon0
star icon0
watch icon0

+ 8 other calls in file

3
4
5
6
7
8
9
10
11
12
13
14




//Support:
// {{VARIABLE}}
async function renderFile(tpl, outfile, datafile) {
    let config = ini.parse(fs.readFileSync(datafile, "utf-8"));
    let content = fs.readFileSync(tpl, "utf-8");
    var matches = [...content.matchAll(/(?<!\$){{\s*(\w+)\s*}}/g)]
    
    for(let m in matches) {
fork icon0
star icon0
watch icon0

75
76
77
78
79
80
81
82
83
84
85
}


function tryConfigPath(configPath) {
  try {
    var data = fs.readFileSync(configPath, 'utf-8');
    var config = ini.parse(data);
    if (config.prefix) return config.prefix;
  } catch (err) {}
  return null;
}
fork icon0
star icon0
watch icon1

176
177
178
179
180
181
182
183
184
185
const iopath =path.resolve(appconfig.sysIniUrl);

let data = fs.readFileSync(iopath);
var str = iconv.decode(data, 'GB2312');
console.log(str);
const Info = ini.parse(str);
console.log('修改ini文件路径', iopath);

Info.config.ProCode = fields['softInfo[ProCode]'];
Info.config.ProName = fields['softInfo[ProName]'];
fork icon0
star icon0
watch icon1

28
29
30
31
32
33
34
35
36
37
const cfgExists = fs.existsSync(cfgPath)
if (!cfgExists) {
  consola.error('Config file not found, creating one...')
  fs.writeFileSync(cfgPath, ini.stringify(config))
} else {
  const parsedConfig = ini.parse(fs.readFileSync(cfgPath, 'utf-8'))
  config.vrchat.client_ip = parsedConfig?.vrchat?.client_ip || '127.0.0.1'
  config.vrchat.client_port = parsedConfig?.vrchat?.client_port || '9000'
  config.vrchat.server_ip = parsedConfig?.vrchat?.server_ip || '0.0.0.0'
  config.vrchat.server_port = parsedConfig?.vrchat?.server_port || '9001'
fork icon0
star icon0
watch icon1