Use require() to Include Node.js Modules
On this page
Important
A complete description of Node.js, modules, and the require() function is out of scope for this tutorial. To learn more, refer to the Node.js Documentation.
You can use the require() function in your MongoDB Playgrounds to include functionality from Node.js modules. You can use modules to import reusable code to simplify your playgrounds.
Require Native Modules
You can require()
native Node modules (such as
fs) in your
Playground without any additional setup or configuration.
Example
The following Playground uses the fs
module to write a document
from the test.employees
collection to a file named
employee.txt
:
const fs = require('fs'); use("test"); const document = db.employees.findOne(); fs.writeFileSync('employee.txt', JSON.stringify(document));
Require Non-Native Modules
To require()
non-native Node modules (such as those downloaded from
npm) you must install the module in one of
the following folders based on your operating system:
Operating System | Module Location |
---|---|
macOS and Linux | One of either:
|
Windows | One of either:
|
Once you install or copy your desired package to one of the module
directories, you can require()
that package.
Example
The following Playground uses the
moment package to write
the current date to a file called date.txt
:
const moment = require('moment'); const fs = require('fs'); const currentDate = moment().format("MMMM DD YYYY"); fs.writeFileSync('date.txt', currentDate);