Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and extracting data from a text file in Javascript

i wanted to know the procedure of how to extract only numerical data from a text file and read it. I have a text file called temperature.txt , and it keeps appending data with the simulation of my code. I want to know a code in javascript to live stream the data into plotly.

'use strict';
var plotly = require('plotly')('agni_2006','jtwubwfjtp');
var initdata = [{x:[], y:[], stream:{token:'g1z4cinzke', maxpoints:200}}];
var initlayout = {fileopt : 'overwrite', filename : 'try'};
plotly.plot(initdata, initlayout, function (err, msg) {
if (err) return console.log(err);
console.log(msg);

var stream1 = plotly.stream('g1z4cinzke', function (err, res) {
    if (err) return console.log(err);
    console.log(res);
    clearInterval(loop); // once stream is closed, stop writing
});
var i = 0;
var loop = setInterval(function () {
    var data = { x : i, y : i * (Math.random() * 10) };
    var streamObject = JSON.stringify(data);
    stream1.write(streamObject+'\n');
    i++;
}, 1000);
});

this is the given example in plotly to live stream the data. i want to put my data values from the .txt file in the y array by reading it.

like image 328
Agnirudra Avatar asked Apr 21 '26 03:04

Agnirudra


1 Answers

This is just one way to read your txt file async with nodeJS and parse the numeric values with a regex

var fs = require('fs'); 

function read(file, cb) {
  fs.readFile(file, 'utf8', function(err, data) {
    if (!err) {
        cb(data.toString().split('\n'))
    } else {
        console.log(err)
    }
  });
}

read(__dirname+ '/temperatures.txt', function(data) {
  var temperatures = [];
  for(var temp in data){
    temperatures.push(+data[temp].match(/\d+/g));
  }
  //your 'loop' logic goes here, y = temperatures
  console.log(temperatures);
});
like image 98
Felix Avatar answered Apr 22 '26 16:04

Felix