Patrick Langkau
Patrick Langkau

Reputation: 47

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

Upvotes: 0

Views: 55

Answers (2)

AcruxCode
AcruxCode

Reputation: 16

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');

Upvotes: 0

namar sood
namar sood

Reputation: 1590

Firstly

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

is not a valid json, you can verify it from here https://jsonlint.com/

Valid json would look like

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

and then you can directly require content of .json file in a variable like

const filedata = require('data/inventur_users.json');

Upvotes: 1

Related Questions