Skip to content
This repository has been archived by the owner on Aug 11, 2022. It is now read-only.

Commit

Permalink
Move the ini-parser from node-core into npm
Browse files Browse the repository at this point in the history
  • Loading branch information
isaacs committed Jun 7, 2010
1 parent 40933cd commit 2cc487d
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 2 deletions.
60 changes: 60 additions & 0 deletions lib/utils/ini-parser.js
@@ -0,0 +1,60 @@
var sys = require('sys')

exports.parse = function parse (d) {
var ini = {'-':{}}
, section = '-'
, lines = d.split('\n')
for (var i = 0, l = lines.length; i < l; i++ ) {
var line = lines[i].trim()
, rem = line.indexOf(";")
if (rem !== -1) line = line.substr(0, rem)
var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i
, match = line.match(re)
if (match) {
if (match[1] !== undefined) {
section = match[1].trim()
ini[section] = {}
} else {
var key = match[2].trim()
, value = (match[3]) ? (match[4] || "").trim() : true
ini[section][key] = value
}
}
}

return ini
}

function safe (val) { return (val+"").replace(/[\n\r]+/g, " ") }

// ForEaches over an object. The only thing faster is to inline this function.
function objectEach(obj, fn, thisObj) {
var keys = Object.keys(obj)
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i]
fn.call(thisObj, obj[key], key, obj)
}
}

exports.stringify = function stringify (obj) {
// if the obj has a "-" section, then do that first.
var ini = []
if ("-" in obj) {
objectEach(obj["-"], function (value, key) {
ini[ini.length] = safe(key) + " = " + safe(value) + "\n"
})
}
objectEach(obj, function (section, name) {
if (name === "-") return undefined
ini[ini.length] = "[" + safe(name) + "]\n"
objectEach(section, function (value, key) {
ini[ini.length] = safe(key) + ((value === true)
? "\n"
: " = "+safe(value)+"\n")
})
})
return ini.join("")
}

exports.encode = exports.stringify
exports.decode = exports.parse
4 changes: 2 additions & 2 deletions lib/utils/ini.js
Expand Up @@ -7,7 +7,7 @@ var fs = require('fs')
, path = require('path')
, http = require('http')
, log = require("./log")
, ini = require("ini")
, ini = require("./ini-parser")
, sys = require("sys")
, hasSSL = false
, crypto
Expand Down Expand Up @@ -67,7 +67,7 @@ function getConfig () {
var config
log(configfile, "configfile")
try {
config = "" + fs.readFileSync(configfile, "utf8")
config = "" + fs.readFileSync(configfile)
// TODO v0.0.8: remove this JSON parse next version
try {
config = JSON.parse(config)
Expand Down

0 comments on commit 2cc487d

Please sign in to comment.