node.jsfsappendfile

I use the appendFile in node js but the File 's condtent is random


This is my code:

var fs = require('fs');
var fs2 = require('fs');
var i;
var slash = '/';
fs.open('target.txt', 'r', function (err, fd) {
    if (err) throw err;
    console.log('file open complete');
});
fs2.open('log2.txt', 'w', function (err, fd) {
    if (err) throw err;
    console.log('file open complete');
})
var array = fs.readFileSync('target.txt').toString().split("\n");

var i = 0;
var slash = ' ';
for (i = 0; i < array.length; ++i) {
    if (i % 2 == 1) {
        var query = array[i];
        if (i != array.length - 1)
            fs2.appendFile('log2.txt', query.substring((query.lastIndexOf(': ') + 2), (query.length - 2)).concat(slash), 'utf-8', function (error) { });
        else if (i == array.length - 1)
            fs2.appendFile('log2.txt', query.substring((query.lastIndexOf(': ') + 2), (query.length - 1)), 'utf-8', function (error) { });
        console.log(query.substring((query.lastIndexOf(': ') + 2), (query.length - 2)));
    }
}

The textfile looks like this:

---->2018-09-12 1. 23818 [] [thread : main] [priority : DEBUG] [category : javasql.ClientSql] [Class : javasql.ClientSql] [method : insertToDb] [ndc : ]- [log content : com.mysql.cj.jdbc.ClientPreparedStatement: insert into db]

This code reads the textfile line by line saves them in an array and parsing even number's DB query and append to a log.txt.

It seems to have worked well, but log.txt file's content is random.

When I run the code in node.js log.txt's content is Insert into values/Create values

but almost run the code in node js

Create valuesInsert into values/

The sequence is changed. I didn't touch target.txt.

Why does this problem happen?


Solution

  • It happens just because appendFile is asynchronous operation. Thus you need either rewrite completely your code or replace appendFile with appendFileSync.