Thursday, 11 May 2017

Problems with prettyjson module, and fs.readFile reading old data

I'm having some problems with the module prettyjson not actually doing what it's supposed to do. I had it working earlier today but, even without changing anything in the .js files it stopped working and I have no idea why.

Basically the prettyjson.render(data, jsonFormatOptions); is supposed to make the JSON data easier to read. Which it has in the past, but currently it does the same as JSON.stringify, and it also adds 3 " in the beginning and end of the data.

Here is a visual,

Before
Before

After
After

Below is the code that is supposed to be formatting the JSON data and send the data in an email.

var jsonFormatOptions = {
  noColor: true,
};

// Makes the json data easier to read
function getData() {
  var prettyJsonData = '';
  fs.readFile('C:/Users/admin/Desktop/Node.js/test/source/json/answers.json',
    'utf8',
    (err, data) => {
      if (err) throw err;
      var prettyJsonData = prettyjson.render(data, jsonFormatOptions);
      makeMail(prettyJsonData);
    }
  );
}

function makeMail(prettyJsonData) {

  // Authenticates the email sender
  var transporter = nodemailer.createTransport({
    host: config.email.host.host,
    port: config.email.host.port,
    secure: config.email.host.secure,
    auth: {
      user: config.email.auth.email,
      pass: config.email.auth.password,
    },
    tls: {
      rejectUnauthorized: false,
    },
    debug: true,
  });

  // Creates email
  let mailOptions = {
    from: config.email.auth.email,
    to: config.email.reciver,
    subject: config.email.title,
    text: `${prettyJsonData}`,
  };

  // Sends email
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return console.log(error);
    }

    console.log('Message %s sent: %s', info.messageId, info.response);
  });
}

module.exports = {
  makeMail: makeMail,
  getData: getData,
};

The other problem is that it sends old data, even tho I've made sure it first writes the data into the JSON file and then, in this code, reads the file. But it still uses the old data. If I remember correctly I accidentally read the file before writing it last time this happened, but I don't see anything wrong with the code now. Here is the whole thing on GitHub if the code below isn't enough (can't have 3 links https://github.com/staryg/ProblemReporter)



via Mikael Kemstedt

No comments:

Post a Comment