Docs Home / VS Code Extension / Explore with Playgrounds / Use require()

Use require() to Include Node.js Modules使用require()包含Node.js模块

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 functionality from Node.js modules. 您可以在MongoDB游乐场中使用require()函数来包含Node.js模块的功能。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.您可以在游乐场中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:以下游乐场使用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()非原生Node模块(例如从npm下载的模块),您必须根据操作系统将该模块安装在以下文件夹之一中:

Operating System操作系统Module 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
Windows

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.一旦您将所需的包安装或复制到其中一个模块目录中,您就可以require()该包。

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);