1

I have files where my logs are in multiple lines every logged event has date, I am trying to write logic if line start with the date and if second line dont have date merge with first line thats the end goal, below code as first step printing lines that has dates vs no dates but it always print else statement, any idea what is implement wrong ?

My question is not about validation of date Object i just want to check if string contains date any format print those lines.Issue is i want to combine multiple lines og event using date parameter.

ctrl.js

fs.readFile(dir + '/' + logFile, 'utf8', function(err, data) {
    var line = data.split('\n');
    var messageDateInfo = line.split('|')[0].replace(/[\[\]']+/g, '');
    var d = parseDate(messageDateInfo);

    function parseDate(str) {
        var m = str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
        return (m) ? new Date(m[3], m[2] - 1, m[1]) : null;
    }
    if (line.includes(d)) {
        console.log('print lines with date', line);
    } else {
        console.log('print lines without date', line);
    }
});

fileData

[2017-03-23T18:13:16Z]|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event { newTopology: 
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341',
     '-0000001342' ],
  oldTopology: 
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341' ],
  workerId: 6,
  pid: 30488 }
[2017-03-23T18:13:16Z]|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event { newTopology: 
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341',
     '-0000001342' ],
  oldTopology: [],
  workerId: 4,
hussain
  • 6,587
  • 18
  • 79
  • 152
  • i edited my question, can you please re-open it i am really struggling on this i used answer from other question e.g `parseDate` – hussain Mar 31 '17 at 16:15

1 Answers1

1

You're using:

str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);

here str = [2017-03-23T18:13:16Z] with those square brackets [],

while str is in ISO date format and you are matching it with 'dd/MM/yyyy' regex that will never match

try using this regex /^(\d{4})\D?(0[1-9]|1[0-2])\D?([12]\d|0[1-9]|3[01])(\D?([01]\d|2[0-3])\D?([0-5]\d)\D?([0-5]\d)?\D?(\d{3})?)?$/

AND

new Date(m[3], m[2] - 1, m[1]) you are returning only day, month & year.

While, comparing it with line which has date and time i.e,18:13:16Z too.

You need to pass those from the array.

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173
Nikhil Zurunge
  • 716
  • 6
  • 10