Write / add data in JSON file using Node.js
If this JSON file won't become too big over time, you should try:
Create a JavaScript object with the table array in it
var obj = {
table: []
};Add some data to it, for example:
obj.table.push({id: 1, square:2});
Convert it from an object to a string with
JSON.stringify
var json = JSON.stringify(obj);
Use fs to write the file to disk
var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback);If you want to append it, read the JSON file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
}});
This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.
UPDATE:
Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback).
With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.
Failed to append data in .json file using node
This error is because you are using the .writeFile in a wrong way.
Try something like this:
fs.writeFile('results.json', JSON.stringify(newData), function(err) {
if (err) throw err;
});
A short explanation:
The ERR_INVALID_CALLBACK in the error message is the missing of the function informed in the last parameter in the example above.
fs.writeFile(<file>, <content>, <callback>)
How do I add to an existing json file in node.js
If you want the file to be valid JSON, you have to open your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.
var fs = require('fs')
var currentSearchResult = 'example'
fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data)
json.push('search result: ' + currentSearchResult)
fs.writeFile("results.json", JSON.stringify(json))
})
write into json file with fs.append
You need to first read the file, in your case you are storing an array in the file. So, you need to push your object to the array that you read from the file, and write the result back to the file (not append):
const fs = require('fs/promises');
// ...
const addToFile = async data => {
let fileContents = await fs.readFile('myJSONFile.json', { encoding: 'utf8' });
fileContents = JSON.parse(fileContents);
fileContents.push(data);
await fs.writeFile('myJSONFile.json', JSON.stringify(fileContents, null, 2), { encoding: 'utf8' });
};
write a json file in nodejs
It seems the path is incorrect and thats why it is not updating the file.
import { writeFile } from 'fs/promises';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export const writeDataToFile = async (filename, content) => {
try {
console.log(filename)
console.log(process.cwd());
console.log(path.join(__dirname, filename)) // check if the path is correct
await writeFile(path.join(__dirname, filename), JSON.stringify(content));
return 'File Updated';
} catch (err) {
console.error(err);
}
}
You might need to await for the file operation to perform:
export const create = (product) => {
const id = uuid()
const newProduct = {...product, id}
products.push(newProduct)
await writeDataToFile('../data/products.json', products)
const promise = new Promise((resolve, reject) => {
const newProduct = products.find(element => element.id = id)
setTimeout(() => {
resolve(newProduct)
}, 1000)
})
return promise
}
How to append JSON data to existing JSON file node.js
Try this. Don't forget to define anchors
array.
var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);
fs.writeFile("testOutput.json", JSON.stringify(json))
How to append data to a JSON with a specific index in javascript/nodejs
If you read from the existing file and parse it with JSON.parse
, you will be able to actually use Array.push
on it. And then you can write the stringified result back into the file:
fs.readFile("./views/scripts/dataVisitorBook.json", function (err, data) {
if (err) throw err;
let data = JSON.parse(data.toString('utf8'));
data = JSON.stringify(data, null, 2);
fs.writeFile("./views/scripts/dataVisitorBook.json", data, { { // dataVisitorBook.json is the storage file
flag:'a' // this flag specify 'please append it' over 'please override file'
}
}, (err) => {
console.log('error :', err)
});
})
It might not be optimal though as it is likely to take more time as the file grows bigger.
add keys to a json file, remove duplicates and write to json file in javascript
First of all to do something you need both data in json
- Make 2 arrays
- Remove duplicates
- Then push data without duplicates.
Put everything together
let allTogether = data.push(...oldUser);
Create unique array
uniq = [...new Set(allTogether )];
Finally set this unique data to specific key
user_follwos.user1 = uniq
Hope this is what you need
Update with example
let user = {
"application_id": "123546789",
"user_follwos": {
"user1": [
"follow1",
"follow2",
"follow3",
"follow4"
],
"user2": [
"followA",
"followB",
"followC",
"followD"
]
}
};
let data = [
"follow5",
"follow6",
"follow7",
"follow8",
"follow9"
];
let oldUser = user["user_follwos"]["user1"];
console.log(`This is old user array`);
console.log(oldUser);
let allTogether = [];
allTogether.push(...data)
allTogether.push(...oldUser);
console.log(`After we put all together`);
console.log(allTogether);
uniq = [...new Set(allTogether )];
console.log(`Getting unique values`);
console.log(uniq);
oldUser = uniq;
console.log(`Now olds user is`);
console.log(oldUser);
Related Topics
Angular2:Render a Component Without Its Wrapping Tag
Using HTML Comment Tag <!-- --> Still Relevant Around JavaScript Code
Javascript: How to Validate Dates in Format Mm-Dd-Yyyy
Save File JavaScript with File Name
JavaScript Getcookie Functions
Keyword 'Const' Does Not Make the Value Immutable. What Does It Mean
Keys in JavaScript Objects Can Only Be Strings
How to Find JavaScript Variable by Its Name
How to Create Every Combination Possible for the Contents of Two Arrays
Style.Display='None' Doesn't Work on Option Tags in Chrome, But It Does in Firefox
Prevent Text Selection After Double Click
Copy/Put Text on the Clipboard with Firefox, Safari and Chrome
Rails 4 Turbo-Link Prevents Jquery Scripts from Working
How to Run Function in Angularjs Controller on Document Ready
Keep Input Value After Refresh Page
How to Make <Input Type="Date"> Supported on All Browsers? Any Alternatives
How to Abort Image <Img> Load Requests Without Using Window.Stop()