Reputation: 5460
My application needs to write the new users who sign up in to a JSON file, so that later I send this file to users.
What I want is something like:
[
{"username": "A"},
{"username": "B"},
{"username": "C"}
]
When a new user "D" signs up, NodeJS will update the file as:
[
{"username": "A"},
{"username": "B"},
{"username": "C"},
{"username": "D"}
]
However I'm having problems to implement this because although I can 'append' to the file, I cannot write a user name just before the closing ']'.
I tried to do without square brackets and JSON.parse(arayFromFileRead) but it gives me an
'unexpected token {'
error.
Could somebody help with either:
Thank you.
Upvotes: 0
Views: 1639
Reputation: 19372
Checkout this example:
var fs = require('fs');
function addUser(user, callback) {
var usersFile = './users.json';
fs.readFile(usersFile, function(err, users) {
if (err) {
return (callback)? callback(err) : console.error(err);
}
users = (users)? JSON.parse(users) : [];
users.push(user);
fs.writeFile(usersFile, JSON.stringify(users), function(err, result){
(callback)? callback(err, result) : console.error(err);
});
});
}
addUser({username: 'D', password: 'blablabla'});
logic:
to have one users.json file where we'll keep all user data serialized by JSON.stringify()
function.
to do so You've to read whole file to variable, parse it, push new record to variable, serialize (stringify) and save it back to file
benefits:
there is no benefit! when Your file will be bigger You'll waste more memory and CPU to read it, push, serialize, write back. also Your file will be locked during read/write
SO BETTER TO DO THIS:
1) create users folder
2) make Your code like this:
var fs = require('fs');
var path = require('path');
var md5 = require('md5');
var usersDir = './users';
function addUser(user, callback) {
var userFile = path.join(usersDir, md5(user.username)+'.json');
fs.writeFile(userFile, JSON.stringify(user), function(err, result){
(callback)? callback(err, result) : console.error(err);
});
}
addUser({username: 'D', password: 'blablabla'});
logic: You have users folder where You keep users records "file per user" way
benefits:
when You've 1 file (users.json) You're having issue of parallel accessing same file.
but when You files are separate, so filesystem itself acts as database, where json file is row and content is document.
Upvotes: 1
Reputation: 1038
In order to write proper JSON (and be able to parse it as such with JSON.parse
), you need to have commas between objects inside an array.
[
{"username": "A"},
{"username": "B"},
{"username": "C"}
]
Upvotes: 2