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

时间:2023-01-22 21:10:35

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

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

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

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

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?

我想拆分我的单个文件代码以便于阅读。我该如何实现这一目标?

2 个解决方案

#1


16  

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

#2


7  

Try:

尝试:

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

or

要么

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

Also, have a look at this blog post.

另外,看看这篇博客文章。

#1


16  

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

#2


7  

Try:

尝试:

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

or

要么

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

Also, have a look at this blog post.

另外,看看这篇博客文章。