如何将单个 Node.js 文件拆分为单独的模块 [英] How to split a single Node.js file into separate modules
问题描述
我想将代码拆分成不同的文件.我目前在同一个文件中编写了所有 get
和 post
方法,但我想要更高的可读性和可管理性.
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:
var Db = require('/filename.js');//...但我不能调用这些方法.
var Db = require('/filename.js'); // ...but I can't call those methods.
我想拆分我的单个文件代码以提高可读性.我如何实现这一目标?
I want to split my single file code for readability. How do I achieve this?
推荐答案
只需查看模块文档:
以/开头寻找绝对路径,例如:
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 与 ./具有相同的效果:
__dirname has the same effect than ./:
require( __dirname + '/module.js');
这篇关于如何将单个 Node.js 文件拆分为单独的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!