Ben Brook Ben Brook - 1 year ago 114
Node.js Question

Node.js require multiple times or pass package as arg?

I have a function in one 'parent' file that calls functions in 10 different 'child' files, all of which

the same 4 packages. Is it better to require those packages once in the parent file and pass those packages in as arguments to the child files, or
them in the top of each of the 10 files?

My instinct is that the former is better, but I don't know if there's some sort of low-level optimization I'm missing, or if there's a big overhead to passing packages as args.

Answer Source

I don't think it really makes a difference. Packages are cached (see

In my opinion, if you require them for each file versus pass them as params depends on how you want to use the child functions. If you may want to utilize the child function outside of the parent at some point, it would be better to require the needed packages in each child. On the other hand, you may have a scenario where you want to call the child function with a param that might change (for instance, you want to pass a sorting function to the child). In that case, a param would be good so you can reuse the bulk of the code.