document
object etc.) Some are still there, like console
(tip: type console
in Node REPL to see available methods)1node
2>
1node file.js
package.json
to store meta info about your package and what packages it may need.node_modules
directory by defaultnode_modules/
folder will always be at the root of the application, thanks to npmCommonJS
for it’s module loader. Using require()
we can get access to built in and 3rd party modules<script>
tags, in Nodejs JavaScript you use require()
to associate with other JavaScript files/modules (aka a Module Loader)1// built in Node module
2var path = require('path'); // no ./ prefix means Node will assume it's either builtin or the a module in the default location (node_modules/)
3
4// 3rd party module downloaded in node_modules/
5var _ = require('lodash');
6
7// a module we created in another file
8var myModule = require('./path/to/my/module'); // you have to prefix with ./
./
.js
at the end, it assumes it’s a JavaScript file by default. If you do put the extension, it’ll still work, but you don’t have to. 1// config.js
2exports.setup = function () {}; // attach things to the `exports` object
3exports.enable = function () {};
4exports.ready = true;
5
6// otherFile.js
7// alternate way: `module.exports` is the entire object
8module.exports = {
9 action: function () {};
10 trigger: true;
11}
exports
object on module
we can expose our code to be required later. To execute node against a file we can run node path/to/file
module.exports
you can not export anything else in that file. module.exports
is the only code that’s going to be exportedexports
it’ll always be an object when you require()
it. So you can have exports.setup
and exports.enable
and exports.ready
(a lot of exported stuff in your module) andmodule.exports
it will be whatever you export on module.exports
, e.g. it can be number 51// config.js
2exports.setup = function () {}; // attach things to the `exports` object
3exports.enable = function () {};
4exports.ready = true;
5
6// otherFile.js
7// alternate way: `module.exports` is the entire object
8module.exports = 3
1var myModule = require('./config'); // this will be an object containing all the exported properties (exports.setup, exports.config, exports.ready)
2var myOtherModule = require('./otherFile'); // this will be whatever you exported with module.exports, in this case: 3
1(function(module, exports, __dirname){
2 // your actual code
3})()
module
and exports
and __dirname
and all of that stuff in your code, because it’s attached that way.1export const m = 1;
1import {m} from “foo”;