Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created March 27, 2012 02:51
Show Gist options
  • Save ishiduca/2212063 to your computer and use it in GitHub Desktop.
Save ishiduca/2212063 to your computer and use it in GitHub Desktop.
parseJSONFile
var fs = require('fs');
module.exports = function parseJSONFile (path, cb) {
if (typeof cb !== 'function') throw('2nd argument must be "Function"');
try {
fs.readFile(path, 'utf-8', function (err, data) {
if (err) throw err;
cb(JSON.parse(data));
});
} catch (e) { throw e; }
};
@ishiduca
Copy link
Author

require.paths.push('../lib');

var parseJSONFile = require('parseJSONFile').parseJSONFile;
var app           = require('myapp');
var configPath    = '../config.json';

parseJSONFile(configPath, function (config) {
    app.start(config.port);
    console.log('Server start to listen on port %s', config.port);
});

@ishiduca
Copy link
Author

var parser = require('./parseJSON');
parser('./path/to/json', function (err, data) {
    console.log(err || data);
});

@ishiduca
Copy link
Author

var parser = require('./parseJSON');
try {
    parser('path/to/json', function (data) {
        console.log(data);
    });
} catch (e) { console.error(e); }

@ishiduca
Copy link
Author

try {
    require('./parseJSON')( 'path/to/json', function (data) {
        console.log(data);
    });
} catch (e) { console.log(e); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment