How can I specify different config files in Node.js? - node.js

try
config = JSON.parse(fs.readFileSync('./config.json', 'ascii'))
catch e
util.debug("Could not parse configuration file.\n" + e.stack)
return
I have that in my node.js code and I have two config files"
config.json.prod
config.json.local
How can I specify that it should run the .local?
By the way, I'm using CoffeeScript

Yea, you certainly can. Checkout nodepad (great reference app):
https://github.com/alexyoung/nodepad/blob/master/app.js
The source comes from this blog series: http://dailyjs.com/2010/11/01/node-tutorial/
Edit: For example
if (app.settings.env == 'production') {
mailer.send(mailOptions,
function(err, result) {
if (err) {
console.log(err);
}
}
);
}
he uses app.settings.env to swap out different environmental/app settings. Same could be used to load a config file. – Chance

Related

Express js adding routes in multiple files

Bit of context: I am learning nodejs/express and have got a small application that in the end should function as an api. I have got a routes directory with a few subdirectories containing files such as Post.js or Users.js, each file defining a few routes for Posts, Users etc.
I have the following bit of code in my index.js placed in routes directly:
public readDir(path, app) {
let dir = path != null ? path : __dirname;
fs.readdir(dir, (err, elements) => {
if(err) throw err;
if(!elements) return;
elements.forEach(element => {
if(element === "init.js") return;
let new_path = x.join(dir, "/", element);
fs.lstat(new_path , (err, stat) => {
if(err) throw err;
if(stat.isDirectory()) {
this.readDir(new_path , app);
} else if(stat.isFile()) {
require(PATH)(app);
}
});
});
});
}
What it does is the following: It reads the Routes directory with each subdirectory by calling itself in a loop and requiring any file that is found (path module is imported as x, I should probably change that sometime). This works fortunately, every route is mapped properly and can be accessed by making a call with postman / insomnia.
My question would be how this could be done better, primarily performance wise whilst still keeping the structure of multiple files and/or directories?
I have already seen this answer and this one and though both seem like great and functional answers I was wondering which would be the better option?
Any pointers would be great!

modify nodejs require() to search for .min.js

O/S is ubuntu 16, node version is 4.2.6.
I have source / development code and run / distribution code, the source.js files are minified and mangled to create equivalent source.min.js files, and I would like for node js require to automatically search for .min.js files as well as .js files.
But as I have a lot of files, I would prefer not to have to go through every require in every file and instead modify the built-in require() function.
This is a very simple implementation of a stand alone function, but how can I modify the built-in function to behave the same way ?
function require(file){
try{return require(file)}
catch(e){return require(file+='.min.js')}
}
You can achieve this by modifying prototype function require of Module class and apply it globally
Here is how you can do it :
var pathModule = require('path');
var assert = require('assert').ok;
module.constructor.prototype.require = function (path) {
var self = this;
assert(typeof path === 'string', 'path must be a string');
assert(path, 'missing path');
try {
return self.constructor._load(path, self);
} catch (err) {
// if module not found, we have nothing to do, simply throw it back.
if (err.code === 'MODULE_NOT_FOUND') {
throw err;
}
// resolve the path to get absolute path
path = pathModule.resolve(__dirname, path+".min.js")
// Write to log or whatever
console.log('Error in file: ' + path);
}
}

fs.open fails with file extension - node.js

I've got the following code:
fs.open("uploads/test.txt", "a", "0755", function(err, fd){
if(err) { console.log(err); }
else {
file.handler = fd; //We store the file handler so we can write to it later
...
}
});
The file is created and written to perfectly when I simply have "uploads/test", but when I try to do "uploads/test.txt" it breaks. Any ideas?
I think you should try using
var path = './uploads/test.txt'.
Or
var path = __dirname + 'your_path';
fs.open(path, "a", "0755", function(err, fd){
if(err) { console.log(err); }
else {
file.handler = fd; //We store the file handler so we can write to it later
...
}
});
This is really silly, but I found what was causing my code to break:
fs.open works as intended. The bug was with my file detection setup using nodemon.
The reason is everytime my app would load it would run the above mentioned code. The code would then write to a new file in my apps /uploads directory. Nodemon would then detect the new file and restart the app thus creating a vicious circle.

gulp plugin looping through all files and folders

OK so I am creating a gulp plugin to create a table of contents and imports for my sass setup.
I have the gulp task all setup like this
var sgc = require('./tasks/sass-generate-contents');
gulp.task('sass-generate-contents', function(){
gulp.src(config.tests + '/**/*.scss')
.pipe(sgc(config.tests + '/_main.scss'));
});
and then my plugin code
function sassGenerateContents(){
return through.obj(function(file, enc, cb){
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
return;
}
console.log(file);
});
}
module.exports = sassGenerateContents;
in my file system (the test directory) are 3 x *.scss files
the console log in the plugin only ever returns the first.
I'm probably missing somehting really obvious here, but I thought the idea of **/* was to loop through the folder structure specified and pull out the files.
Can someone explain to me why it's only returning the first file?
Thanks
I was missing the callback function, which called back to itself. At the end of the function i needed to ad
return cb();

Meteor: How to separate local environment from production?

I have two pieces of code: one that must only be run in a local environment and the other in production. What is the best way to do that in Meteor?
You can check do
(server side)
var isDevelopment = function() {
var i = WebApp.clientProgram.manifest.length;
while(i--) {
if('sourceMap' in WebApp.clientProgram.manifest[i]) return true;
}
return false;
}
if(isDevelopment()) {
console.log("Dev mode");
}else{
console.log("Production");
}
The idea is to check for JS Source Maps, which are only available in dev mode. This should work out of the box with your meteor app without any special configuration.
I prefer to set an environment variable which the server can read. For example:
$ METEOR_ENV="production" meteor
Then on the server:
if (process.env.METEOR_ENV === 'production') {
// production code here
} else {
// dev code here
}
If you have only two states, you could assume !production = dev.
Use this package and you will haveMeteor.isdevelopment only in development. There is other packages out there too that do the same thing but differently. this is the simplest

Resources