Read and Write file using vs code extension - json

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.

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.

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.

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.

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.

Related

How vscode parses json files that are used for extension configurations?

How VSCode parses json files like language-configuration.json that is used to describe language extensions? I see that these files contain comments and many, like typescript, contain trailing commans.
If such content is parsed using JSON.parse() the error will be raised.
I implement an extension that reads these config files and like to use the same parsing method that is used in vscode.
Thank you
I would assume they use the jsonc-parser - since it is written by one of the vscode team and has 3 million+ downloads a week.
npm package: jsonc-parser
I use it myself because I need to parse complicated custom settings that might have comments in them for example.
Add the package to your dependencies. npm install --save jsonc-parser
Then import it (I have it in a js extension for now):
const jsonc = require("jsonc-parser");
const rootNode = jsonc.parseTree(document.getText());

What would be the best way to write JSON in a locally stored file in React Native

Im currently working on a new design for a mobile app (only frontend). In the project I need to use states to change the css of a button. If the button has changed, next time the app is refreshed the state should be as you left it.
That is why I have a locally stored JSON file that is structured the same as how the apps current database is. Reading it is no issue, but I can't get the writing to work.
How I read the JSON:
const jsonData = require('../data.json')
function GetBaseState(id){
console.log(jsonData.bases[id].state)
}
How would I go about changing that state in the JSON file?
In order to both of reading and writing Json file , you are able to use react-native-fs. For example by readFile method you can read json file and by writeFile method writing your json file in local storage.
react-native-fs have good documents that you are able to reading that for more information and usage.

Loading JSON files in React, without JSON extension

I'm trying to require some JSON files in my React app (based on CRA 3.01 with Typescript).
The normal const obj = require('./path/file.json') would work if my files had a .json extension - however, these files have .md for 'metadata' and a couple other extensions, and the standard require isn't working. The files are from a tool, so changing to .json isn't a practical option.
Doing some research, it seems the approach is to use the webpack json-loader module (the webpack json-loader docs says that working with different file extensions is the main reason for using the module). I found an example and am using this:
const context = require.context(
"json-loader!./metadata",
true,
/^\.\/.*\.md$/
);
const metadata = context("./foo.md");
I've got a minimum reproduction here (see App.tsx):
https://github.com/ericsolberg/testjson
It seems that this is correctly using the json-loader, and finding the file correctly. However, I'm getting a syntax error:
Error: Module build failed (from ./node_modules/json-loader/index.js):
SyntaxError: Unexpected token m in JSON at position 0
at JSON.parse (<anonymous>)
at Object.module.exports (/Users/***/projects/jsontest/node_modules/json-loader/index.js:4:49)
I did some research on this error, and believe the problem is that the file is being parsed twice - first by the loader configured by CreateCreactApp's default webpack config, then by the specified JSON loader.
I don't want to eject my CRA app to modify the webpack config, and would like to avoid a re-wire hack (and whatever other issues that introduces) ... does anyone know of a way to load JSON files in a CRA app, if these files don't have a JSON extension?
Here's the solution that ended up working for me.
I could eject my project, of course, and customize the webpack config to load JSON files with other extensions. It may be possible to make a rewire hack work as well.
But I realized that when I require a file that is not one of the extensions recognized by CRA's config, it instead copies that file into the build, and require('file.ext') returns the URL of the file. So I'm using axios to load the file. This means a trip to the server for something that could be done statically, but for where I'm taking this project that is actually OK (eventually it will load metadata from a server anyway).

Getting a path of accessed script in Dart

The aim is to create a config file for server-side Dart application, which can be imported as needed into scripts like so:
import 'Config/config.dart';
What is crucial for this config script however, is that it knows it's own location when being accessed with an import (not the location of the file accessing it). Currently it uses this line below to find the path:
final String ROOT_DIR = dirname(Platform.script.toFilePath());
However, this returns the file path of the file importing it and not the file that is being imported. This needs to be known purely for working out a relative path to the root folder, which will allow other absolute paths to be known in the config file (such as routes, controllers, and things), like so:
final String PUBLIC_DIR = join(ROOT_DIR, 'Public');
final String VIEWS_DIR = join(ROOT_DIR, 'Views');
What would be the best way of approaching this? I have seen this post: Get script path in Dart (analog __DIR__ constant in PHP) which is the same sort of situation, however I can't see a clean way of using relative paths to find the route folder.
Probably missing something really obvious, but can't see it at the moment. Any help would be much appreciated, thank you for reading.
This is not supported in Dart.
Maybe Mezoni found some kind of trick to get this information which he packed in his caller_info package https://stackoverflow.com/a/24880092/217408.
You can't rely on the path where the files are stored during development.
Currently it is only experimental but when you run dart2dart on your code, all or many parts of the code are inlined.

Reading files with Node.js from input file type selector

I am trying to select files using input file type and then upload them to dropbox using the dropbox Core API or saving it to a local folder using Node.JS readFile and writeFile methods. The problem is that most of these methods require the file path and all I have is the name of the file that is stored in the File object array and for what I have read browsers do not allow to get the full path for security reasons. I don't know how to go about this, can anyone help me solve this? Thanks!!