0

Even though I can clearly see my output in console. I can't write them into a file. There is 1 output file and its undefined-03-02-2017.txt which contains single line '15:33 undefined'.

for (i = 0; i < channelcount; i++) {
    messages[i] -= messagesOld[i];
    console.log(channels[i] + ' ' + messages[i]);
    messages[i] = messagesOld[i];

    fs.open('logs/' + channels[i] + '.txt', 'r', function (err, fd) {
        if (err && err.code == 'ENOENT') {
            fs.writeFile('logs/' + channels[i] + '-' + moment().format('MM-DD-YYYY') + '.txt', moment().format('H:mm') + ' ' + messages[i], function (err) { });
        } else {
            fs.appendFile('logs/' + channels[i] + '-' + moment().format('MM-DD-YYYY') + '.txt', moment().format('H:mm') + ' ' + messages[i] + '\n', function () { });
        }
    });
}
Pyro
  • 17
  • 10

2 Answers2

0

@Pyro, you used writeFile incorrectly. Please see syntax writeFile(file, data[, options], callback)

you have to use like this

fs.writeFile('logs/' + channels[i] + '-' + moment().format('MM-DD-YYYY') + moment().format('H:mm') + '.txt ' , messages[i], function (err) { });

0

fs.open() is an async function. So your entire loop will run before the first callback actually gets called. By that time i equals channelCOount + 1 and channels[ channelCount + 1 ] is undefined.

You can either wrap the callback into a closure, use a let if you can use ES6, or use fs.openSync()

Shilly
  • 8,511
  • 1
  • 18
  • 24