Friday, July 22, 2016

Little-known capability of require

require can also read JSON file for you:
let c = path.join(os.homedir(), 'connection.json');

let connectionJson = require(c);

let connectionString =
        'postgres://'
        + connectionJson.user
        + ':' + connectionJson.password
        + '@' + connectionJson.host
        + '/' + connectionJson.database;

let massiveInstance = massive.connectSync({connectionString: connectionString});
app.set('db', massiveInstance);

So no more need to open and read the JSON file manually:
let c = path.join(os.homedir(), 'connection.json');

fs.readFile(c, 'utf8', (err, data: any) => {

    console.log(data);

    let connectionJson = JSON.parse(data);

    let connectionString =
            'postgres://'
            + connectionJson.user
            + ':' + connectionJson.password
            + '@' + connectionJson.host
            + '/' + connectionJson.database;

    let massiveInstance = massive.connectSync({connectionString: connectionString});
    app.set('db', massiveInstance);
});



Happy Coding!

No comments:

Post a Comment