Sunday, 9 April 2017

Nodejs, require module from within a function, or at top of script. Which is better for custom modules?

I'm writing a custom script which contains all my common used settings and functions. One of these functions takes a timestamp and returns a human readable date with a custom format using Moment.

My custom script is in the node_modules folder and the file is called settings.js for example. Now, I know I can include this at the top of any of my scripts using

var settings = require('settings.js);

and get my function by

settings.timestamp_to_date(timestamp,function(date){console.log(date})

What I don't know is the best place to include the additional modules (moment, and moment-timezone). I have them in the function call now so that they don't load on every single app requiring the settings.js file. My thought here is that it won't load that module into memory for apps that don't need it.

This has me wondering though, for apps that might use this function a lot, it'd be requiring the modules every single time the function is ran, which itself seems like a poor choice.

Which is the best option to accomplish what I'm after by having all my functions in a single file, and loading the required modules for the function only when the certain app needs it?

If it means in each app I have to declare which modules I'll want to use before including settings.js then that's not ideal. My apps so far are just learning apps for myself. Nothing I create currently will be used by many people.

What's the best option for low use apps, and what's the best for apps that might get high use in a production environment?



via Branndon

No comments:

Post a Comment