即使路径正确也无法访问javascript文件

时间:2021-05-24 20:23:00

标签: javascript node.js filepath

这似乎是 Nodejs 的一个常见问题,我尝试了所有解决方案都没有成功。 我的 require('filepath') 请求失败,出现错误“ENOENT: no such file or directory, open "a filepath" 例如我有这些文件夹:

enter image description here

我想使用 action1.js 和 data.json 到 folder2 action2.js

所以虽然需要相对路径不起作用(为什么?):

const action1 = require('../folder1/action1.js')
const data = require('../../data/data.json')     

我试过绝对路径,但也行不通

const action1 = require(path.join( __dirname,'../folder1/action1.js'))
const data = require(path.join( __dirname,'../../data/data.json'))   

我做错了什么?

2 个答案:

答案 0 :(得分:0)

代码看起来正确,但我建议您检查目录的范围。

您可以尝试以下步骤从 action2.js 中查看您的目录结构

npm install directory-tree

在您的文件中添加以下几行:

const dirTree = require("directory-tree");

const tree1 = dirTree('../');
console.log(tree1);

const tree2 = dirTree('../../');
console.log(tree2);

这可能会帮助您找到目录的范围。这不是解决方案,而是帮助您进行调试的一种方式。

答案 1 :(得分:0)

好的,我找到了我的问题。它来自另一个文件的另一个需求。我这里的代码是正确的。

抱歉问了一个愚蠢的问题,请原谅我是菜鸟,谢谢你的回答。