require and readFile async - node.js

I'm using express and I want to put some configurations in a file(like database configuration, api credentials and other basic stuffs).
Now I'm putting this configuration in a JSON and I read this file using readAsync.
Reading some code I noted a lot of people use don`t use a JSON.. Instead, they use a common JS file and exports in a module.
Is there any difference between these approaches, like performace?

The latter way probably simplifies version control, testing and builds, and makes it easier to have separate configurations for production and development. It also lets you do a little "preprocessing" like defining "constants" for common setups.
In a well-designed application, the performance of configuration-reading is going to be completely irrelevant.
If you go with the latter, you need to practice some discipline: a configuration module should consist almost entirely of literals, with only enough executable code to handle things like distinguishing between development and production. Beware of letting application logic creep into it.

In node.js require works synchronously, but it's not very important if you load configurations once on the application starts. Asynchronously way realy need only if you loading configurations many times (for each request for example).

In node.js you can simply require your json files:
config.json:
{
"db": "127.0.0.1/database"
}
app.js:
var config = require('./config');
console.log(config);
If you need something more full featured I would use flatiron/nconf.

Related

Avoid singleton in Node.js?

I've read several times that a singleton should be avoided as much as possible. By singleton I mean this kind of code
exports = module.exports = new Passport();
This code is from the Node.js module PassportJS. It allows us to use passport and add some var that will be shared inside our entire code.
So as you can see we can make this code:
https://github.com/ragulka/sails-starter-app/blob/master/api/controllers/SessionController.js
(This is just an example, I do too and I blame no one).
Note that he is taking passport at the top of the file with require and then using one of the strategies that have been added previously in the code. Obviously it's convenient but is it the best way to do this?
Is there no way to pass passport variable inside controllers from previous code?
Let me know if something is not clear.
Thanks in advance.
There are cases like this, a passport instance, an express app instance, a mongodb connection pool, a logger instance, etc, where the most common case is a single instance per node process. In these situations, a singleton can be convenient and keep code concise, provided the module also provides an easy way to access and call the constructor for those minority times you want more than one instance (like if your app wants to 2 distinct pools of connections to 2 distinct mongodb databases, or 2 different log streams, for example).
This can sometimes be inconvenient for testing, mocking, stubbing, etc, though.
Is there no way to pass passport var inside controllers from previous code ?
Yes, there is. When you do var passport = require("passport"); you will always get back the exact same singleton instance, including all it's internal state as configured by other code in your application. This is due to the caching that happens in the node require call. What takes extra code is if you want to create a new distinct Passport instance, in which case you need to call the constructor yourself.

Best way to access config.json file in YUI

I am learning YUI and was wondering what is the best way to access my configurations (stored in a json) using YUI.
One way I came across was to maintain it in the config/app.json and access it with using global variable:
Y.Object.getValue(App, ['Cache', 'globals', 'context'])
Is this the best way? Also if my configuration is spread out over multiple json files, what would be the best way to access them?
Thanks
There are basically two ways to do this:
Include the configuration in the HTML page
Load the configuration using Ajax
Both have some pros and cons.
Including the configuration in the HTML
This requires you to do some server side coding that reads the JSON file and prints it in the page as a global variable. This is what you seem to be doing. The upside of this is that you don't have to make an extra HTTP request. The downside is that you're relying on global variables which can be fragile.
if you're using Node.js you can use express-state to expose that configuration to the client. Alternatively you can use express-yui which relies on a similar mechanism to generate YUI configuration.
Using Ajax
The downside of using Ajax is that it's slower, but the upside is that you can trust the information to be new and not have been modified by anything else in your page.
Dealing with multiple configuration files
My recommendation is that you merge the configuration into a single object. Just decide on some convention for which one wins and generate a single configuration object. This will simplify handling that information in the client. You can do this easily with express-state by just calling app.expose(config1); app.expose(config2) and so on.

Best practices for using ExpressJS middleware across a number of different files in NodeJS app

If I wanted to utilise useful middleware like express.cookieParser(); and suchlike, am I expected to be economical with my instances of express when splitting my NodeJS application up into different files.
For example, if I use var express = require('express') in one file, and again in many others, am I wasting resources fetching these and re-instantiating them? Or does require cache modules, or (even better) create a global instance of them?
I know the performance impact of requiring express on multiple files would probably be negligible - this is more of a question to help me understand how modules load.
When you require a module twice, the second require uses the cached exports object that was called earlier.
Source: http://docs.nodejitsu.com/articles/getting-started/what-is-require

Express: Best way to share a JS config file between client and server

I have a config.js file that has all my app settings inside it. Some of these settings need to be shared with front-end scripts as well as back-end.
I have some confidential variables that I don't want to be exposed to the front-end though. Do any NodeJS/ExpressJS wizz kids have any good solutions to this?
Do you keep your common config data in a /public location and confidential server-side data separate above the exposed /public folder?
Thanks guys
Using express-expose to share (or 'expose') data from the server to the client works pretty well. As Raynos said, I would keep confidential variables as environment variables and then you may be able to safely expose all of your settings.
Or you can do something like create a 'shared' object in your settings. Like this:
app.set('shared', {
setting1: mydata
, setting2: new OAuth(...)
, setting3: { ... }
});
Which allows you to access the settings as app.setting.shared.setting1 on the server and then you can app.expose(app.setting.shared) so your client side JS can access the same object.
You can either use express-expose to share your variables with the frontend or you can use browserify and share your settings in a module.
I have some confidential variables that I don't want to be exposed to the front-end though.
I generally have confidential variables defined in environment variables. This also solves the problem of committing / hard coding these variables in version control.
There is also express-state from Yahoo, it lets you
share configuration and state data of an Express app with the
client-side via JavaScript
It is well documented and the readme contains a lot of useful examples

Per-server NodeJS configuration

I have our first NodeJS server that's being deployed to a client server along with the rest of the application. I have a few items that need to be configured on a server-specific basis but I'm unable to find any easy way to handle this.
On googling I've found a few choices - using a framework that has support built in (too late), setting up a configuration file that can be loaded (would work, but I don't want to have to worry about keep one config file for each server we have and keeping those out of git).
I'd love to just have node determine what the request domain is (dev.ourdomain vs www.ourdomain) and just do a condition. It sounds easy, it likely IS easy, but I'm having trouble finding any way to determine that domain data.
As #drachenstern mentioned, you could use request.headers.host, as in:
# get the path portion of the URI without optional port
var domain=request.headers.host.replace(/\:\d+$/,'');
but this wouldn't provide a canonical domain if the request was made using an IP address rather than the server's name.
A better option might be to use the hostname of the server, as in:
var domain=process.env[
process.env['OS'] && process.env['OS'].match(/^Win/) ? 'HOSTNAME' : 'HOST'
];
You might consider if request.host has the data you need. It most likely would.
why don't you just hardcode that information in a init.js and change it for each server? How often are you going to move the servers to need to do this? Just do this
init.js
module.exports = { domain: "dev.ourdomain"};
main.js
var domain = require( "init.js" ).domain;
I assume you are developing it on dev.ourdomain and dumping it on www.ourdomain. Just ignore dumping init.js so that the server's init version remains ^_^ This is what I do and it saves me the need to bloat the project with another module just for one command.
Hope this helps others who encounter this situation.

Resources