Pregunta

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);
      });
¿Fue útil?

Solución

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.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top