23

i am building an extension to parse json using vs code extension. so my need is ,it should be able able to load .json file from a particular folder and iterate through content of the file. Then it should allow user to select few keys from it make a new json file out of this and save it in any folder.

But i am not able to find any way to read and write files in "vs code extension".Could someone please help me.

user6639252
  • 261
  • 1
  • 2
  • 9

4 Answers4

28

If you want to read the current edit state of a file you can use the following API workspace function:

vscode.workspace.openTextDocument(uri).then((document) => {
  let text = document.getText();
});

This will show you the current state of the file including unpersisted changes. document is of type TextDocument and has isDirty set to true if it has pending changes.

Matthias
  • 13,607
  • 9
  • 44
  • 60
Steffen
  • 3,327
  • 2
  • 26
  • 30
7

Since the extension runs in nodejs, you should be able to use any nodejs module built-in or installed by npm in the usual way.

For your purpose you will be OK with the built-in fs module: https://nodejs.org/dist/latest-v6.x/docs/api/fs.html

In your extension you will need to import the required module, so your code file should contain this:

let fs = require("fs");

and then use the methods in the usual way, eg. fs.fileReadSync( filename, encoding ) ...

Please not that there is one exception. If you install a nodejs module containing compiled, binary code, it will not run in the extension and instead you will see an error message saying something like %1 is not a valid Win32 application. Pure javascript modules are OK, though.

5

VSCode extensions are running in node.js. Therefore you can use any available node.js package/module within your extension. For instance, check out this question for reading JSON.

Community
  • 1
  • 1
seairth
  • 1,966
  • 15
  • 22
1

For JSON, you just need to require or import the JSON file, such as:

const jsonObject = require('./myJSONfile.json');
// do something

For JSON with comments, you can use node-jsonc-parser.

After the manipulation, you could use the fs module of nodej.js to write to the disk.

Nonoroazoro
  • 310
  • 5
  • 7