1

I'm trying to store X and Y values from a text file in an Array using NodeJS, but I actually have no clue how to do it ..

The text file looks as follows:

X        Y
385      0.12567 
386      0.25786 
387      0.35789 
388      0.45798 
...      .......

So I'm trying to get Arrays looking like that:

arr[x]= 385, 386, 387, 388 ...  
arr[y]= 0.12567, 0.25786, 0.35789, 0.45798  ..  

I hope you can help me!

JS

VisioN
  • 143,310
  • 32
  • 282
  • 281
JSt
  • 799
  • 2
  • 10
  • 21

1 Answers1

2

You could do something like this:

var fs = require('fs');

function readLines(input, done) {
    var arr = [];
    var remaining = '';

    input.on('data', function(data) {
        remaining += data;
        var index = remaining.indexOf('\n');
        while (index > -1) {
            var line = remaining.substring(0, index);
            remaining = remaining.substring(index + 1);
            func(line);
            index = remaining.indexOf('\n');
        }
    });

    input.on('end', function() {
        if (remaining.length > 0) {
            func(remaining);
            done(arr);
        }
    });

    function func(data) {
        arr.push(data.split(/\s+/g));
    }
}

var input = fs.createReadStream('test.txt');
readLines(input, done);

function done(arr) {

    var obj = {};
    var key1 = arr[0][0];
    var key2 = arr[0][1];
    obj[key1] = [];
    obj[key2] = [];

    arr.shift();

    arr.forEach(function (item) {
        obj[key1].push(item[0]);
        obj[key2].push(item[1]);
    });

    console.log('X:', obj['X']);
    console.log('Y:', obj['Y'])
}

Output:

X: [ '385', '386', '387', '388' ]
Y: [ '0.12567', '0.25786', '0.35789', '0.45798' ]


See: node.js: read a text file into an array. (Each line an item in the array.)

Community
  • 1
  • 1
Ali
  • 473
  • 2
  • 7