【问题标题】:Context for "relative paths" seems to change to the calling module if a module is imported如果导入模块,“相对路径”的上下文似乎会更改为调用模块
【发布时间】:2019-02-08 16:47:08
【问题描述】:

我的目录结构如下:

home/
├── module1/
│   ├── index.js
│   └── file.csv
└── module2/
    └── index.js

模块 1 index.js 的代码使用名为 csvtojson 的节点模块读取 file.csvmodule2/index.js 需要 module1/index.js

当我直接从 module1 运行代码时,一切正常并且文件被成功读入。但是,当我在 module2 中运行代码时,我得到一个“文件不存在”。错误。我是否需要明确地将所有路径设为绝对路径?

【问题讨论】:

  • 请通过edit将您的问题设为minimal reproducible example,以包含相关代码。
  • 请至少提供您所有的require()fs.readFile() 行以及使用的路径。

标签: javascript node.js node-modules relative-path


【解决方案1】:

我在使用 csvtojson 时也遇到了完全相同的问题。

每当您使用文件的普通路径时,都会相对于调用者脚本进行搜索,但使用 require 时除外,据我所知,它仅适用于源文件和 json。 p>

但是您可以选择使用 __dirname 来获取使用它的特定脚本的绝对目录,因此您可以像这样获得正确的路径:

const yourPath = __dirname + "/file.csv";

【讨论】:

    猜你喜欢
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多