var proj = {
Name : "abc",
Roll no : 123
};
How can I write proj data in JSON format in .json file in javascript?
You can save the json object in file.json file like this.
const FileSystem = require("fs");
FileSystem.writeFile('file.json', JSON.stringify(proj), (error) => {
if (error) throw error;
});
JSON.stringify (introduced in ES 5.1) will convert the object into a string of JSON.
var json = JSON.stringify(proj);
JavaScript has no built-in mechanism for writing to a file. You generally need something non-standard provided by the host environment. For example, Node.js has the writeFile method of the File System module.
Pretty much the same as top answer but slightly simpler version I regularly use to help with debugging (prints out an object at a given point in the code without using a debugger):
require('fs').writeFile('file.json', JSON.stringify(proj), (error) => {
if (error) {
throw error;
}
});
Related
I download an OpenAPI file from localhost and convert it to .json. It becomes something like this:
"components":{"responses":{"r200":{"content":{"application/json":{"schema":{"properties" ....
I'm doing this using this JavaScript code:
const processData = async () => {
const req = await axios.get('http://localhost:5004/swagger');
let reqJson = JSON.stringify(req.data);
fs.writeFile('swagger.json', reqJson, (err) => {
if (err) throw err;
})
}
processData()
If there are any changes in the OpenAPI file on localhost, I want to download it, convert to .json, save it as a new file and compare with the original swagger.json. It will be the same to previous code, but
fs.writeFile('newSwagger.txt' ....
And changes has to be in error field in url.
Question: How can I compare these files, and show any changes in a popup on a web site like:
Attention: there is changes in Backend API:
Missing api/xxx/yyy
Added api/zzz/yyy
Is it possible to convert FileEntry to standard JavaScript object File?
I can't find anything meaningful in documentation https://developer.chrome.com/apps/fileSystem
The FileEntry documentation does provide guidance here:
The FileSystemFileEntry interface of the File System API represents a
file in a file system. It offers properties describing the file's
attributes, as well as the file() method, which creates a File object
that can be used to read the file.
Unfortunately file()method relies on callbacks rather Promises, but we can wrap that and make using the API (and reading the code) easier:
async function getFile(fileEntry) {
try {
return new Promise((resolve, reject) => fileEntry.file(resolve, reject));
} catch (err) {
console.log(err);
}
}
// From inside an async method or JS module
let file = await getFile(fileEntry); // Wait until we have the file
I found how to do this in google examples https://github.com/GoogleChrome/chrome-app-samples/blob/master/samples/filesystem-access/js/app.js
var jsFileObject;
fileEntry.file(function (file){
jsFileObject = file
});
I am making a program in nwjs, which will be used to reading part of .json file and showing it + giving possibility to edit it.
And I don't know how can I read, show and edit part of .json file.
Any ideas?
var filesystem = require('fs');
Then refer to the Node documentation here: NodeJS FS
You'll want to load the json file into an object, and then save changes to the file periodically or manually, rather than constantly loading and saving the file.
You can use the jsonfile package to read and write the object.
Read JSON file to object:
var jsonfile = require('jsonfile');
var file = '/path/to/file.json';
jsonfile.readFile(file, function(err, someData) {
if (err) {
// don't use someData
// it's not populated
return;
}
// do something with someData
// there was no error
console.log(someData);
});
Write object to JSON file:
var jsonfile = require('jsonfile');
var file = '/path/to/file.json';
var data = { name: 'John Doe', age: 50, eyes: 'brown', hair: 'black' };
jsonfile.writeFile(file, data, function (err) {
// an error occurred
console.error(err);
});
Best practice is to validate complex data using JSON-schema validation. There are countless JSON editor tools available on GitHub such as JSON Editor Online and Treema. These have been implemented in JavaScript and jQuery and shouldn't prove difficult to follow.
I am currently requiring a JSON file which I am reading data from.
var allUORHours = require('./UORHoursAch.json');
How do I then write to the file? The below doesn't make any changes to the file
allUORHours.test = {};
You may use the File System API's writeFile():
https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
No, of course it doesn't. It just changes the variable's value. To write a JSON, you would need to convert to JSON, then write to a file:
var fs = require('fs');
fs.writeFile('./UORHoursAch.json', JSON.stringify(allUORHours), function (err) {
if (err) {
console.log(err);
} else {
console.log("Saved");
}
});
I am very new to node.js and I think I understand the basics of how it functions but I feel like I am not seeing something that is vital to how fs.write and buffers function.
I am trying to send a user defined variable over socket.io and write it into an html file. I have a main site that has the button, when clicked it sends the information to the socket in a variable.
The thing I can't figure out is how to insert the variable into the html file.
I can save strings that I type, into a file:
(e.g.) var writeBuffer = new Buffer ('13');
But not variables that I put in:
(e.g.) var writeBuffer = new Buffer ($(newval));
I even tried different encoding methods, I think I am missing something.
Server.js
var newval = "User String";
var fd = fsC.open(fileName, 'rs+', function (error, fd) {
if (error) { throw error }
var writeBuffer = new Buffer($(newval));
var bufferLength = writeBuffer.length;
fsC.write( fd, writeBuffer, 0, bufferLength, 937,
function (error, written) {
if (error) { throw error }
fsC.close(fd, function() {
console.log('File Closed');
});
}
);
});
If you are using a version of jsdom 4.0.0 or later, it will not work with Node.js. As per the jsdom github readme:
Note that as of our 4.0.0 release, jsdom no longer works with
Node.js™, and instead requires io.js. You are still welcome to install
a release in the 3.x series if you use Node.js™.