Created
October 20, 2011 22:29
-
-
Save NuckChorris/1302585 to your computer and use it in GitHub Desktop.
PHP var_export() reading in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sys = require('sys'); | |
var fs = require('fs'); | |
var parseConfigFile = function (str) { | |
str = str.replace('<?php', ''); | |
str = str.replace('?>', ''); | |
str = str.replace(';', ''); | |
str = str.replace('return ', ''); | |
str = str.replace(/'([a-zA-Z0-9\_\-]+)'\s+=>\s/g, '"$1": '); | |
str = str.replace(/array \(/g, '{'); | |
str = str.replace(/\)/g, '}'); | |
str = str.replace(/\s+/g, ' '); | |
str = str.replace(/,\s*}/g, '}'); | |
str = str.replace(/'([^\r\n'""]*)'/g, '"$1"'); | |
return JSON.parse(str); | |
}; | |
var Config = function (filename) { | |
this._filename = filename; | |
console.log('Loading %s...', filename); | |
this.load(function (err, data) { | |
if (err) return _this.emit('error', err); | |
_this.emit('load', data); | |
console.log('%s loaded!', filename); | |
}); | |
var _this = this; | |
fs.watchFile(filename, function (curr, prev) { | |
if (curr.mtime === prev.mtime) return; | |
console.log('Reloading %s...', filename); | |
_this.load(function (err, data) { | |
if (err) return _this.emit('error', err); | |
_this.emit('load', data); | |
console.log('%s loaded!', filename); | |
}); | |
}); | |
}; | |
sys.inherits(Config, process.EventEmitter); | |
Config.prototype.load = function (cb) { | |
this.obj = {}; | |
var _this = this; | |
fs.readFile(this._filename, 'utf8', function (err, data) { | |
if (err) return cb(err); | |
try { | |
var config = parseConfigFile(data); | |
_this.obj = config; | |
return cb(null, config); | |
} catch (err) { | |
return cb(err); | |
} | |
}); | |
} | |
module.exports = Config; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment