Question

i want parse a json file to Dictionary and want write some data to it. this is what i have, but i become a empty Dictionary

var users = {};

      fs.readFile('login.json', function read(err, data) {
        if (err) {
            throw err;
        }
        users = JSON.parse(data);
      });
Était-ce utile?

La solution

In Node.js you can require JSON files, so your code could simply become:

var users = require('./login.json');

Though note the data will be cached, so if your login.json file changes without an application restart the users object will stay the same.

Autres conseils

readFile is an asynchronous function. If you want to do anything with the data in it, you must do so in the callback function (or at some point after you know the callback has been run).

You may want to use readFileSync instead.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top