如何将单个 Node.js 文件拆分为单独的模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14000898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:48:15  来源:igfitidea点击:

How to split a single Node.js file into separate modules

node.jsnpm

提问by Raj

I want to split the code into different files. I currently write all getand postmethods in the same file, but I want greater readability and manageability.

我想将代码拆分为不同的文件。我目前在同一个文件中编写所有getpost方法,但我想要更高的可读性和可管理性。

I've tried to put the code in different files, but while running the main app, the rest of getand postmethods in other files are not able to called. I include this:

我试图将代码放在不同的文件中,但是在运行主应用程序时,其他文件中的其余部分getpost方法无法调用。我包括这个:

var Db = require('/filename.js'); // ...but I can't call those methods.

var Db = require('/filename.js'); // ...但我不能调用这些方法。

I want to split my single file code for readability. How do I achieve this?

我想拆分我的单个文件代码以提高可读性。我如何实现这一目标?

回答by Sebastian vom Meer

Just have a look at the module documentation:

看看模块文档

Starting with / looks for absolute paths, eg:

以 / 开头查找绝对路径,例如:

require('/home/user/module.js');

./ starts with the path where the calling file is located.

./ 以调用文件所在的路径开头。

require('./lib/module.js');

__dirname has the same effect than ./:

__dirname 与 ./ 具有相同的效果:

require( __dirname + '/module.js');

回答by Ofiris

Try:

尝试:

var Db = require('./filename.js');

or

或者

var Db = require('filename.js');

Also, have a look at this blog post.

另外,看看这篇博文