3

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.

3
  • How your .txt looks like? Commented Jul 27, 2015 at 16:03
  • The temperature value is 26 The temperature value is 21 The temperature value is 16 the output is like this. I want to extract the values and put them in y Commented Jul 27, 2015 at 17:37
  • You can try to read the file with nodejs and then parse the numeric value with a regex. Commented Jul 28, 2015 at 19:03

1 Answer 1

5

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.