Open and print a CSV file using Javascript
In this example, we will export two data loggers in CSV format using JavaScript and EVENTS programming, and we will print the contents of the CSV files to the log.
-
Navigate to HSYCO Manager
-
Go to "Code Editor"
- Click "New Events File"
- Give it a name ("files.txt"for example) and click "New File"
- Copy the following code and save the file:
INIT : {
function getTimestamp90DaysAgo() {
// Current date
var now = new Date();
// Subtract 90 days (in milliseconds)
var ninetyDaysAgo = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
// Calculate current year,month,day,hours,minute
var year = ninetyDaysAgo.getFullYear();
var month = (ninetyDaysAgo.getMonth() + 1).toString();
var day = ninetyDaysAgo.getDate().toString();
var hours = ninetyDaysAgo.getHours().toString();
var minutes = ninetyDaysAgo.getMinutes().toString();
// Add a zero if value < 10
month = month.length < 2 ? '0' + month : month;
day = day.length < 2 ? '0' + day : day;
hours = hours.length < 2 ? '0' + hours : hours;
minutes = minutes.length < 2 ? '0' + minutes : minutes;
// Generate timestamp
return year + month + day + hours + minutes;
}
function readCSVFile(filepath){
// Load Java libraries
var FileReader = Java.type('java.io.FileReader');
var BufferedReader = Java.type('java.io.BufferedReader');
var File = Java.type('java.io.File');
// Create a file object
var file = new File(filepath);
// Inizializza un BufferedReader per leggere il file
var reader = new BufferedReader(new FileReader(file));
// read line by line
var line;
while ((line = reader.readLine()) !== null) {
// Ignore comments "#"
if (!line.startsWith("#")) {
messageLog("READCSV: current line: " + line);
}
}
// Close BufferedReader
reader.close();
}
}
#every day at midnight
TIME 0000 : {
messageLog("CSVEXPORT - procedure start");
var timestamp = getTimestamp90DaysAgo();
messageLog("CSVEXPORT - 90 days ago timestamp: " + timestamp);
//export dataloggers in export folder
dataLoggerSave("csvwrite from " + timestamp + " groupby day" , ["dataloggerid1", "dataloggerid2"], "export", true);
//wait for export
sleep(5000);
//check if CSV files are in the folder
readCSVFile("export/dataloggerid1.csv");
readCSVFile("export/dataloggerid2.csv");
}