Difference between revisions of "Nodejs"
From John Freier
(Created page with "== How to use Require == Require will cache objects after it calls them, kind of like a singleton pattern. To build out an object that require can grab there are a couple of...") |
|||
| Line 32: | Line 32: | ||
}; | }; | ||
module.exports = exampleService; | module.exports = exampleService; | ||
| + | |||
| + | |||
| + | Then you can call them from your script like so. | ||
| + | const exampleService = require('./service/example'); | ||
| + | exampleService.print(); | ||
| + | |||
| + | You don't need to add the .js but I think you have to start with '.' directory. | ||
Latest revision as of 12:27, 5 January 2023
How to use Require
Require will cache objects after it calls them, kind of like a singleton pattern.
To build out an object that require can grab there are a couple of different ways.
The following way will create an object based on a function so it can have private variables.
example.js
const exampleService = (function() {
const self = this;
self.print = function() {
console.log('...');
}
return this;
})();
module.exports = exampleService;
Another way is to create a kind of JSON object with functions.
example.js
const exampleService = {
name: 'example',
print: function() {
console.log('...');
}
};
module.exports = exampleService;
Then you can call them from your script like so.
const exampleService = require('./service/example');
exampleService.print();
You don't need to add the .js but I think you have to start with '.' directory.