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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With