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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With