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.
Related
I am trying to make an extension for chrome and one of the needed functionality is to make it possible to save user's data locally (But I do plan to integrate Gdrive saving). I wanted to save user's data into CSV assuming that it would be easier but it turned out a disaster.
I have tried many different methods in order to make it possible but it seems like it's no use.
Here's part of the code that doesn't work:
var { parse } = require('csv-parse');
const fs = require("chrome-fs");
const records = [];
const csvFile = chrome.runtime.getURL("save_file.csv");
var parser = parse({ columns: true }, function(err, records) {
console.log(records);
});
fs.createReadStream(chrome.runtime.getURL("save_file.csv")).pipe(parser);
and here's an error that browser throws at me when I try to initialize this code:
Uncaught Error
at chrome.js:511:1
if (err.name === 'NotFoundError') {
var enoent = new Error()
511: enoent.code = 'ENOENT'
callback(enoent)
I'm trying to look for a way to create a .txt File object without saving it to disk in Node.js. In browser I'd do something like
new File(['file_contents'], 'file_name.txt', {type: 'text/plain'})
The end aim is to create a .txt file object temporarily for my Discord Bot to send as a message attachment.
From the discord.js documentation, I presume I'm supposed to create a Buffer or Stream object representing the file.
I'm already using require('node-fetch') library to read attachments in messages, if that has any relevancy (but can't see anything in their docs on this either).
After playing around in console I've found Buffer.from('string of txt file contents') to represent the file seems to work fine.
Usage:
channel.send(new Discord.MessageAttachment(Buffer.from('Hello World'), 'file_name.txt'))
In order to write a text file in JS you should use the fs library, included in Node.js.
Here is an example of writing to a file:
fs = require('fs');
let content = "Hello world!";
fs.writeFile('file.txt', content, function (err) {
if (err) return console.log(err);
// Code here will execute if successfully written
});
Then in order to send a local file to Discord you can use .send with an object containing a files property in it, like this:
channel.send({
files: [{
attachment: 'entire/path/to/file.txt',
name: 'file.txt'
}]
}).then(() => {
// Delete file
fs.unlink('file.txt');
});
You can see more about .send() here and you can find more about the fs module here
I just want to store my json data in a file in a particular directory using JS. I can not see the created file using the following code.
var jsonse = JSON.stringify(submitted);
var blob = new Blob([jsonse], {type: "application/json"});
var file = new File([blob], "" + workerID + ".json")
JS Documentation Link would also suffice.
Assuming you're not using a web browser which cannot write to your file system for, hopefully obvious (another question), security reasons.
You can redirect output from your script to a file.
node yourfile.js > output_file.json
Or you can use the fs module.
Writing files in Node.js
// note jsonse is the json blob
var fs = require('fs');
fs.writeFile("/tmp/test", jsonse, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
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 have a few clients that will be using my website, and I want each client to have their own "config" file (EX: location=1 for one computer, location=2 for another). I want to do this using a file I place on the client's machine and then when they access the website the client looks on their own machine and figures out what to load based on what's in that file. This file can be a CSV file, plain text file, or any other kind of file that it needs to be for this to work.
Looking online all I've seen is stuff with file uploader. I don't want them to have to select the file, just have the file contents load and call a javascript function when they do.
Example of file
Location=1
AnswerToQuestion=42
and another file
Location=2
AnswerToQuestion=15
and my JS function
var setAnswerToQuestion = function(answer){
locationConfig.setAnswer(answer)
}
Take a look at localstorage. It's a persistent key/value system that the browser implements to keep data for your website/webapp.
The Basic Principle:
To set a variable:
localStorage.setItem('answer_1', '42');
To get a variable:
localStorage.getItem("answer_1");
I guess if you have lots of answers you would end up with an array/object something like this:
var answers = [42, 15];
Towards a Solution:
You could store and retrieve that by using JSON.stringify
localStorage.setItem('answers', JSON.stringify(answers));
var answers = JSON.stringify(localStorage.getItem('answers'));
Be Educated
Smashing Magazine has a tutorial here
Dive into HTML5 has a tutorial here
You can't access files on local machines without using "file upload". You could store your config files on browser localstorage as:
var getConfigData = function() {
return JSON.parse(localStorage.getItem('config'));
}
var saveConfigData = function(config) {
localStorage.setItem('config', JSON.stringify(config));
}
var addDataToConfig = function(key, value) {
var config = getConfigData();
config[key] = value;
saveConfigData(config);
}
var config = {
Location: 1,
AnswerToQuestion: 42
};
// save new config
saveConfigData(config);
// add new data to config
addDataToConfig('name', 'John Doe');