require()
to Include External Modules¶On this page本页内容
MongoDB for VS Code is currently available as a Preview in the Visual Studio Marketplace. The product, its features, and the corresponding documentation may change during the Preview stage.
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 modules which exist in separate files.
You can require()
native Node modules (such as fs) in your Playground without any additional setup or configuration.
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));
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.
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);