Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CoffeeScript instead of JSON? For configuration files etc

JSON really is a pain to use for local configuration files as it does not support comments or functions, and requires incredibly verbose syntax (commas, always use " for keys). Making it very error prone, or in the case where functions are required, impossible to use.

Now I know that I could just do:

require('coffee-script')
config = require('config.coffee')

However, that requires me to do module.exports = {the data} inside config.coffee which is less than ideal. And even allows for things such as require to be exposed which can make the configuration files insecure if we do not trust them.

Has anyone found a way to read coffeescript configuration files, but keep them secure?

like image 204
balupton Avatar asked Aug 19 '12 03:08

balupton


1 Answers

Turns out CoffeeScript has support for the security part built in via setting the sandbox argument to true via the eval call. E.g.

# Prepare
fsUtil = require('fs')
coffee = require('coffee-script')

# Read
dataStr = fsUtil.readFileSync('path').toString()
data = coffee.eval(dataStr, {sandbox:true})

The above code will read in the file data, then eval it with coffeescript in sandbox mode.

I've created a nice wrapper for this called CSON which supports coffee and js files via require, and cson files via the above mechanism, and json files via the typical JSON.parse - as well as stringifying the values back to coffeescript notation. Using this, the following API is exposed:

# Include CSON
CSON = require('cson')

# Parse a file path
CSON.parseFile 'data.cson', (err,obj) ->  # async
result = CSON.parseFile('data.cson')  # sync

# Parse a string
CSON.parse src, (err,obj) ->  # async
result = CSON.parseSync(src)  # sync

# Stringify an object to CSON
CSON.stringify data, (err,str) ->  # async
result = CSON.stringifySync(obj)  # sync
like image 82
balupton Avatar answered Sep 18 '22 05:09

balupton