'Node.Js write and read Array to/from File

i have a NodeJs applet that I want to save the Users Array (Contains Objects) to a File, I am doing this with:

const fs = require('fs');
const util = require('util');
fs.writeFileSync('data/inventur_users.json', util.inspect(users), 'utf-8');

The Output in the File inventur_Users.json is:

[ BU4AFLx3cUYqdjvYPci7: { id: '5LkOWtVFcqz29UpsAAAC',
    name: '[email protected]',
    rechte: 'vollzugriff',
    client_ID: 'BU4AFLx3cUYqdjvYPci7' } ]

Now I am Reading the file back in with this code:

filedata = fs.readFileSync('data/inventur_users.json', 'utf-8');

My Problem is that i only get a String and I don't know how to convert the String back to an Array that contains Objects.

Thanks in advance, Patrick



Solution 1:[1]

You can use JSON.parse() to convert the string back to a JavaScript object:

filedata = JSON.parse(fs.readFileSync('data/inventur_users.json', 'utf-8'));

You should also use JSON.stringify() to save the file in the first place:

fs.writeFileSync('data/inventur_users.json', JSON.stringify(util.inspect(users)), 'utf-8');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AcruxCode