Docs Home → MongoDB for VS Code
Use require()
to Include External Modules使用require()
包含外部模块
require()
to Include External ModulesOn this page本页内容
A complete description of Node.js, modules, and the require()Node.js、模块和require() function is out of scope for this tutorial.
函数的完整描述超出了本教程的范围。
To learn more, refer to the Node.js Documentation.要了解更多信息,请参阅Node.js文档。
You can use the require()您可以在MongoDB Playgrounds中使用 function in your MongoDB Playgrounds to include modules which exist in separate files.
require()
函数来包含存在于单独文件中的模块。
Require Native Modules需要原生模块
You can 您可以在演练场中require()
native Node modules (such as fs) in your Playground without any additional setup or configuration.
require()
原生节点模块(如fs
),而无需任何额外的设置或配置。
The following Playground uses the 以下Playground使用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));
See also:
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下载的模块),必须根据操作系统将模块安装在以下文件夹之一中:
macOS and Linux |
|
Windows |
|
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以下演练场使用moment package to write the current date to a file called
date.txt
:包将当前日期写入名为
date.txt
的文件:
const moment = require('moment');
const fs = require('fs');
const currentDate = moment().format("MMMM DD YYYY");
fs.writeFileSync('date.txt', currentDate);