【问题标题】:VS Code extension code unable to find JSON pathVS Code 扩展代码找不到 JSON 路径
【发布时间】:2018-07-15 18:51:38
【问题描述】:

我正在尝试创建一个需要(或导入;))从本地 JSON 文件读取数据的 vs 代码扩展。我将 JSON 保存在根文件夹中(与我的 extension.jspackage.json.gitignore 等相同的文件夹)。我的代码使用fs包读取JSON文件,但是当我在构造函数中运行命令时,出现以下错误,

Error: ENOENT: no such file or directory, open 'fieldIds.json'

我在某处读到文件路径是相对于节点开始的文件夹的。当我运行 VS Code 时,我不确定从哪个文件夹节点开始。但是如果我将我的 JSON 放在那个文件夹中,那么这应该工作吗?如何指定我只想从特定路径(例如桌面?)运行 JSON。

我尝试将我的 JSON 文件移动到与 VS Code 编辑器 settings.json 相同的文件夹,但这也没有用。

/Users/<user>/Library/Application Support/Code/User

这是我的文件夹结构的样子

...这是扩展程序的代码

const vscode = require('vscode')
const fs = require('fs')

function activate (context) {
  // 'fieldIds.json' not found    
  const json = fs.readFile('fieldIds.json', 'utf8', (res) => console.log(res))
  console.log(JSON.stringify(json))

  ...
  context.subscriptions.push(...)
}

帮助。

【问题讨论】:

  • 当前目录不是你想的那样。考虑使用require.resolve()

标签: javascript visual-studio-code vscode-extensions


【解决方案1】:

您应该确保您的当前工作目录与放置fieldIds.json 的位置相同。因为fs模块最终会从当前工作目录读取文件。

如果你真的想读取同目录下的文件,可以考虑使用下面的代码:

const path = require('path')

...

fs.readFileSync(path.resolve(__dirname, "fieldIds.json"), "utf8")

上面的代码 sn-p 会找到与extension.js相同目录fieldIds.json,因为__dirname是当前执行脚本的路径。

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 2020-10-08
    • 1970-01-01
    • 2023-03-05
    • 2021-06-04
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多