Use require() to Include External Modules

Info With Circle IconCreated with Sketch.Note

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.

Important With Circle IconCreated with Sketch.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 modules which exist in separate files.

You can require() native Node modules (such as fs) in your Playground without any additional setup or configuration.

Beaker IconExample

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');
const document = db.employees.findOne();
fs.writeFileSync('employee.txt', JSON.stringify(document));
Bulb IconTip

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 SystemModule Location
macOS and Linux

One of either:

  • $HOME/.node_modules
  • $HOME/node_modules
  • $HOME/.vscode/extensions/node_modules
  • $HOME/.vscode/extensions/mongodb.mongodb-vs-code-<version>\node_modules

One of either:

  • C:\Users\.node_modules
  • C:\Users\node_modules
  • C:\Users\<user>\node_modules
  • C:\Users\<user>\.vscode\extensions\node_modules
  • C:\Users\<user>\.vscode\extensions\mongodb.mongodb-vscode-<version>\node_modules

Once you install or copy your desired package to one of the module directories, you can require() that package.

Beaker IconExample

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);
Bulb IconTip
Give Feedback