javascript - VS Code extension code unable to find JSON path
问题描述
I'm trying to create a vs code extension that requires (or imports ;)) to read data from a local JSON file. I've kept the JSON in the root folder (same folder where I have my extension.js
, package.json
, .gitignore
, etc). My code uses fs
package to read the JSON file, but when I run the command in constructor, I get the following error,
Error: ENOENT: no such file or directory, open 'fieldIds.json'
I read somewhere that the file path is relative to the folder from where node starts. I'm not sure from which folder node starts when I run my VS Code. But if I place my JSON in that folder, then should this work? How do I specify that I want to run the JSON from a specific path only (eg, Desktop?).
I tried to move my JSON file to the same folder as VS Code editors settings.json
, but that didn't work either.
/Users/<user>/Library/Application Support/Code/User
Here's what my folder structure looks like
...and here's the code from extension
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(...)
}
Help.
解决方案
You should make sure your current working directory is the same as where fieldIds.json
is placed. Because the fs
module eventually reads files from the current working directory.
If you really want to read a file in the same directory, consider using the following code:
const path = require('path')
...
fs.readFileSync(path.resolve(__dirname, "fieldIds.json"), "utf8")
The above code snippet will find fieldIds.json
that is placed in the same directory with extension.js
since __dirname
is the path of the currently executing script.
推荐阅读
- javascript - 将纪元时间转换为日期 - MomentJS
- c# - 使用 JSON.NET 将部分 json 反序列化为 C# 中的数据表
- jquery - 延迟加载背景图片,去掉data-src onload
- python - Tensorflow 检查哪些示例预测正确,哪些预测不正确(混淆矩阵的种类)
- javascript - .net Jquery CheckBox onchange 事件失去价值
- java - 如何使用spring data mongo db在mongodb中创建视图
- java - 如何使用 APDU 读取和下载 ddd 行驶记录仪文件?
- python - 尝试过滤输入
- django - Django 模型:@property
- zapier - Zapier 触发器:如果只有一个选项可用,则跳过输入字段的用户输入