سؤال

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);
      });
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top