Reputation: 1770
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.
Upvotes: 1
Views: 2972
Reputation: 181
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.
Upvotes: 3