Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 236 Vote(s) - 3.67 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to update a value in a json file and save it through node.js

#1
How do I update a value in a json file and save it through node.js?
I have the file content:

var file_content = fs.readFileSync(filename);
var content = JSON.parse(file_content);
var val1 = content.val1;

Now I want to change the value of `val1` and save it to the file.
Reply

#2
//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));
Reply

#3
// read file and make object
let content = JSON.parse(fs.readFileSync('file.json', 'utf8'));
// edit or add property
content.expiry_date = 999999999999;
//write file
fs.writeFileSync('file.json', JSON.stringify(content));
Reply

#4
For those looking to add an item to a json collection

function save(item, path = './collection.json'){
if (!fs.existsSync(path)) {
fs.writeFile(path, JSON.stringify([item]));
} else {
var data = fs.readFileSync(path, 'utf8');
var list = (data.length) ? JSON.parse(data): [];
if (list instanceof Array) list.push(item)
else list = [item]
fs.writeFileSync(path, JSON.stringify(list));
}
}
Reply

#5
I would strongly recommend not to use synchronous (blocking) functions, as [they hold other concurrent operations][1]. Instead, use asynchronous [fs.promises][2]:

```js
const fs = require('fs').promises

const setValue = (fn, value) =>
fs.readFile(fn)
.then(body => JSON.parse(body))
.then(json => {
// manipulate your data here
json.value = value
return json
})
.then(json => JSON.stringify(json))
.then(body => fs.writeFile(fn, body))
.catch(error => console.warn(error))
```

Remeber that `setValue` returns a pending promise, you'll need to use [.then function][3] or, within async functions, the [await operator][4].

```js
// await operator
await setValue('temp.json', 1) // save "value": 1
await setValue('temp.json', 2) // then "value": 2
await setValue('temp.json', 3) // then "value": 3

// then-sequence
setValue('temp.json', 1) // save "value": 1
.then(() => setValue('temp.json', 2)) // then save "value": 2
.then(() => setValue('temp.json', 3)) // then save "value": 3
```


[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

[4]:

[To see links please register here]

Reply

#6
Save data after task completion
```
fs.readFile("./sample.json", 'utf8', function readFileCallback(err, data) {
if (err) {
console.log(err);
} else {
fs.writeFile("./sample.json", JSON.stringify(result), 'utf8', err => {
if (err) throw err;
console.log('File has been saved!');
});
}
});
```
Reply

#7
Doing this asynchronously is quite easy. It's particularly useful if you're concerned with blocking the thread (likely). Otherwise, I'd suggest Peter Lyon's answer

```ts
const fs = require('fs');
const fileName = './file.json';
const file = require(fileName);

file.key = "new value";

fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
if (err) return console.log(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
});
```

The caveat is that json is written to the file on one line and not prettified. ex:

```json
{
"key": "value"
}
```

will be...

```json
{"key": "value"}
```
To avoid this, simply add these two extra arguments to `JSON.stringify`

```ts
JSON.stringify(file, null, 2)
```

`null` - represents the replacer function. (in this case we don't want to alter the process)

`2` - represents the spaces to indent.
Reply

#8
Promise based solution [Javascript **(ES6)** + Node.js **(V10 or above)**]


const fsPromises = require('fs').promises;
fsPromises.readFile('myFile.json', 'utf8')
.then(data => {
let json = JSON.parse(data);
//// Here - update your json as per your requirement ////

fsPromises.writeFile('myFile.json', JSON.stringify(json))
.then( () => { console.log('Update Success'); })
.catch(err => { console.log("Update Failed: " + err);});
})
.catch(err => { console.log("Read Error: " +err);});

If your project supports Javascript **ES8** then you could use **asyn/await** instead of native promise.
Reply

#9
addition to the previous answer add file path directory for the write operation

fs.writeFile(path.join(__dirname,jsonPath), JSON.stringify(newFileData), function (err) {})
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through