Docs HomeMongoDB for VS Code

Use require() to Include External Modules使用require()包含外部模块

Important

A complete description of Node.js, modules, and the require() function is out of scope for this tutorial. Node.js、模块和require()函数的完整描述超出了本教程的范围。To learn more, refer to the Node.js Documentation.要了解更多信息,请参阅Node.js文档

You can use the require() function in your MongoDB Playgrounds to include modules which exist in separate files.您可以在MongoDB Playgrounds中使用require()函数来包含存在于单独文件中的模块。

Require Native Modules需要原生模块

You can require() native Node modules (such as fs) in your Playground without any additional setup or configuration.您可以在演练场中require()原生节点模块(如fs),而无需任何额外的设置或配置。

Example

The following Playground uses the fs module to write a document from the test.employees collection to a file named employee.txt:以下Playground使用fs模块将test.employees集合中的文档写入名为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:require()非本机节点模块(例如从npm下载的模块),必须根据操作系统将模块安装在以下文件夹之一中:

Operating System操作系统Module Location模块位置
macOS and LinuxOne of either:其中之一:
  • $HOME/.node_modules
  • $HOME/node_modules
  • $HOME/.vscode/extensions/node_modules
  • $HOME/.vscode/extensions/mongodb.mongodb-vs-code-<version>\node_modules
WindowsOne 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.一旦您将所需的包安装或复制到其中一个模块目录中,就可以要求()该包。

Example

The following Playground uses the moment package to write the current date to a file called date.txt:以下演练场使用moment包将当前日期写入名为date.txt的文件:

const moment = require('moment');
const fs = require('fs');

const currentDate = moment().format("MMMM DD YYYY");

fs.writeFileSync('date.txt', currentDate);