[英]How to locate the right path for a .js file when using require
I have an ExpressJS project where I want to use .js module inside another. 我有一个ExpressJS项目,我想在另一个项目中使用.js模块。 I use require to get the .js module but it can't find the module because the path is not correct.
我使用require获取.js模块,但由于路径不正确而无法找到该模块。 How can I see or find what is the correct path for a local module.
如何查看或找到本地模块的正确路径。
Here is my project hierarchy/structure 这是我的项目层次结构
This is what I have tried inside programController.js - another thing is I don't quite understand using "." 这是我在programController.js内部尝试过的-另一件事是我不太了解使用“。” in path string.
在路径字符串中。
var Program = require('.././program.js');
var FinishProgram = require('.././finishProgram');
The .
的
.
and ..
notation in paths represent a path relative to the file they're being required from. 路径中的
..
表示 相对于它们所需要的文件的路径。
Meaning of .
的含义
.
and ..
Wildcards 和
..
通配符
.
- inside the same directory this file is in (also referred to as the current working directory) -该文件位于同一目录内(也称为当前工作目录)
..
- inside the parent directory of the current directory ..
当前目录的父目录中
When you use multiples of these together it creates a relative path pattern. 当您将它们的倍数一起使用时,它将创建一个相对路径模式。 So for
programController.js
to access program.js
your path should be 因此,为了使
programController.js
访问program.js
您的路径应为
var Program = require('../../models/program');
This path means, go up 2 folders to the App
directory and locate the models
folder, then load the file program.js
. 此路径意味着将两个文件夹上移到
App
目录并找到models
文件夹,然后加载文件program.js
。
Following the same rules, you can also access finishProgram.js
按照相同的规则,您还可以访问
finishProgram.js
var FinishProgram = require('../../models/finishProgram');
.
represents the current directory and is redundant in your case. 代表当前目录,在您的情况下是多余的。
The paths are simple relative paths that are used to determine how to navigate to the required files. 这些路径是简单的相对路径,用于确定如何导航到所需文件。
This should work for you: 这应该为您工作:
var Program = require('../../models/program');
var FinishProgram = require('../../models/finishProgram');
Note that the extension .js
is not required. 请注意,不需要扩展名
.js
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.