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下载的模块),您必须根据操作系统将该模块安装在以下文件夹之一中:
| macOS and Linux |
|
| Windows |
|
Once you install or copy your desired package to one of the module directories, you can 一旦您将所需的包安装或复制到其中一个模块目录中,您就可以require() that package.require()该包。