Reading and retrieving data from a text file in Javascript
I wanted to know how to extract only numeric data from a text file and read it. I have a text file called temperature.txt and it keeps adding data with a simulation of my code. I want to know the code in javascript in order to translate data into a plot.
'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 example given in plotly for data flow transfer. I want to put my data from a .txt file into a y array while reading it.
+3
source to share
1 answer
This is just one way to read an asynchronous txt file using nodeJS and parse numeric values ββusing 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);
});
+3
source to share