Say I have one .js
file containing a javascript object. I want to be able to access that object and all of its functionality from another .js
file in the same directory. Can I simply export this object with the module.exports
object and require()
it in the other .js
file? If this is possible can you give me an example?
If it helps I'm developing with node.
This is the way I create modules:
myModule.js
And to use this module in another JS file, you can simply use
require
and use your object as normal:someFile.js
Of course you can. In my example I use obj to hold my config info. I put it in a file called
index.js
inconfig
folder. This makes the index the preferred choice to be picked when Iimport 'config'
. I have 2 exports here one for my node and api stuff and the other for my db. You can ignore the first bit where I set the environment.Calling
import config from '../config';
will pick the default one. And if I specify I can get thedb
exportimport { db } from '../config';
In one file:
In the other:
Everything in a js file on node is local to that file unless you put it in the export object. This actually is very different from JavaScript in a browser--in the browser all files that get imported act together like one big file.
You can kinda think about node files as though you are creating a module object and passing it' into a function surrounding your code.