Node Red multiple values to influxDB - javascript

i try with Node Red to build an query to send multiple values to an influxDB from a loop with this code:
var inputArray = msg.payload;
var lenInputArray =inputArray.length;
var modbusStartRegister = 14000;
var sendString = "";
var msg93 ={};
for (i = 0; i < lenInputArray; i++) {
var actRegister = modbusStartRegister +i;
var actValue = inputArray[i];
if ( i >=1){
sendString = sendString + " ,"
}
sendString = sendString +"{register: " + actRegister +"," +"value: " + actValue +"}";
if ( i ==(lenInputArray-1)){
sendString = sendString + "]"
}
}
msg93.payload = sendString;
return msg93
But the insert in the influxDB is one line it looks at them interpreted as an complete string. How can I build or convert the string that the DB accept them as individual entry? Thanks for the help

This is because you are building a string, node an object.
You can build the array object on the fly like this:
var inputArray = msg.payload;
var lenInputArray =inputArray.length;
var modbusStartRegister = 14000;
var payload = [];
var msg93 ={};
for (i = 0; i < lenInputArray; i++) {
var temp = {};
temp.register = modbusStartRegister +i;
temp.value = inputArray[i];
payload.push(temp);
}
msg93.payload = payload;
return msg93

Related

App Script create array from email string

Using app scripts I'm trying to extract all the email addresses from email messages and put them in an array. From my console.log messages, I'm getting stuck because it looks like instead of an array I just get a string. i'm not too familiar with javascript. Any help would be great. I'm looking for an array of email address. The methods of message.get() return a string. I want to split out the email address and create a single, unified array.
var ui = SpreadsheetApp.getUi();
function onOpen(e){
ui.createMenu("Gmail Manager").addItem("Get Emails by Label", "getGmailEmails").addToUi();
}
function getGmailEmails(){
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
var fullArray = [];
for(var i = threads.length - 1; i >=0; i--){
var messages = threads[i].getMessages();
for (var j = 0; j <messages.length; j++){
var message = messages[j];
if (message.isUnread()){
fullArray.push(extractDetails(message));
}
}
}
console.log("FullArray:"+fullArray);
for(var i=0; i<fullArray.length; i++){
console.log("printing array " + i + ": "+fullArray[i])
}
}
function extractDetails(message){
var dateTime = message.getDate();
var subjectText = message.getSubject();
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmail = message.getReplyTo();
var toEmail = message.getTo();
var emailArray = []
var senderArray = senderDetails.split(',');
var ccArray = ccEmails.split(',');
var replyArray = replyEmail.split(',');
var toArray = toEmail.split(',');
for (var i =0 ; i<toArray.length; i++){
console.log("toArray Loop"+ i + " : "+ toArray[i]);
emailArray.push([toArray[i]]);
}
for (var i =0 ; i<ccArray.length; i++){
console.log("ccArray Loop"+ i + " : "+ ccArray[i]);
emailArray.push([ccArray[i]]);
}
console.log("Email Array: "+ emailArray);
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, senderDetails, subjectText, ccEmails,replyEmail,toEmail,emailArray]);
return emailArray;
}
I think the problem is just the console output. If you change console.log("Email Array: "+ emailArray); to console.log("Email Array: ", emailArray);, then it shows an array of arrays. You could simplify your extract method as follows:
function extractDetails(message) {
/* ... */
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmails = message.getReplyTo();
var toEmails = message.getTo();
let emailArray = [senderDetails, ccEmails, replyEmails, toEmails].reduce(
(array, string) => {
//remove names (like "Name <name#company.com>") and filter empty values
let emails = string
.split(/\s*,\s*/)
.map(e => e.replace(/.*?([^#<\s]+#[^#\s>]+).*?/g, "$1"))
.filter(Boolean);
if(emails.length > 0)
return array.concat(emails)
return array
}, []);
/* ... */
}

Creating dynamic variable in JavaScript for URLs

My current variable 'theurl' has a given static URL. I'd like to pass through URLs through the variable. The main issue is that the URL that i want are created through entering a value on a separate website. Is there an way of retrieving the URL this way or is it completely terrible?
The website i want to retrieve the produced URL from is https://cloud.timeedit.net/ltu/web/schedule1/ri1Q7.html#
from there i enter the code 'A0033H' in the search field next to the drop down menu with 'kurs/program' (in swedish) selected.
At the moment I've checked out the passing value between two html pages.
<script type="text/javascript">
var HttpClient = function () {
this.get = function (aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function () {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open("GET", aUrl, true);
anHttpRequest.send(null);
}
}
var theurl = 'https://cloud.timeedit.net/ltu/web/schedule1/ri166XQ2505Z5YQv250132Z6yQY820653YX5Y3gQ3076757.json';
var client = new HttpClient();
client.get(theurl, function (response) {
var response1 = JSON.parse(response);
//alert(response);
var test = JSON.stringify(response);
var test2 = test.replace(/,/g, " ");
var test3 = test2.replace(/}/g, " ");
var test4 = test3.replace(/{/g, " ");
var test5 = test4.replace(/"/g, " ");
var test6 = test5.replace(/ /g, " ");
var test7 = test6.replace(/\\/g, " ");
var test8 = test7.replace(/ \ /g, " ");
var test9 = test8.replace(/\ /g, " ");
var test10 = test9.replace(/]/g, " ");
var test11 = test10.replace(/\[/g, " ");
var test12 = test11.replace(/" "/g, '');
//alert(test12);
// this is the string variable
var wordLength = test12.length; // we use the length method to store the length of the word string in a variable
document.write('<table>');
document.write('<tr><th>Lektioner</th></tr>');
for (i = 0; i < wordLength; i++) {
var indexNr = test12.indexOf('id', i += 100);
var indexNr2 = test12.indexOf('id', i += 200);
//alert(indexNr);
//alert(indexNr2);
var substring = test12.substring(indexNr, indexNr2);
// alert(substring);
var j = 200;
var indexNr4 = test12.indexOf('columns', j += 110);
var indexNr3 = test12.indexOf('id', j += 110);
var substring2 = test12.substring(indexNr4, indexNr3);
document.write('<tr><td>' + substring + '</td></tr>');
}
document.write('</table>');
});
</script>
The produced result gives me the JSON format structured in a table as strings.
I know this is severe spaghetti code, but I'm just wondering if the retrieval of the URL is possible?

How do I build my JSON object using two parts when concatenated together produces the correct JSON data path

Is this possible to do, or how do I do it?
arrayElement = new Object();
JSONkey = jsonData.table[0].key; // key in table[0] is "ident/Lesson/Value"
JSONkey = JSONkey.replace(/\//g, '.'); // now JSONkey is "ident.Lesson.Value"
arrayElement.JSONkey = "value1" // Can I do this or how would I?
So arrayElement.JSONkey is the same as arrayElement.ident.Lesson.Value
arrayElement = new Object();
JSONkey = jsonData.table[0].key; // key in table[0] is "ident/Lesson/Value"
JSONkey = JSONkey.replace(/\//g, '.'); // now JSONkey is "ident.Lesson.Value"
deepRef(arrayElement, JSONkey, "value1");
function deepRef(ref, key, value) {
var segments = key.split("."),
n = segments.length;
for (var i=0, skey; i<n; i++) {
skey = segments[i];
if (i < n - 1) {
ref[skey] = {};
ref = ref[skey];
} else {
ref[skey] = value;
}
}
}

compressing string in js and save in localStorage

I'm trying to save a HUGE json string in my localStorage but for some reason sometimes it saves it and sometimes not, I thought I should compress it so I took an LZW implementation in js from one of the threads in stackoverflow.
The problem is when I try to localStorage.setItem() the compressed string it gives me an error "Invalid argument", any idea why or what should I do?
Edit:
this is the code I'm using:
// LZW-compress a string
function lzw_encode(s) {
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++) {
currChar=data[i];
if (dict[phrase + currChar] != null) {
phrase += currChar;
}
else {
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++) {
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}
// Decompress an LZW-encoded string
function lzw_decode(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
this is the code that calls the compressing algorithm and saves it in LS
LOG("GetMerchantList(): Done");
var SITESVAR = unescape(data)
localStorage.setItem("MYSITES", lzw_encode(SITESVAR)); //this throws error
IWT.BuildMerchantList(SITESVAR);

Adobe AIR readLine

I need to process a text file one line at a time. In BASIC, I could use a readline command, which would read until the next carriage return/line feed.
How would you write a function for looping through a file one line at a time in AIR?
var myDir = air.File.documentsDirectory;
var myFile = myDir.resolvePath("Test.txt");
if (myFile.exists) {
var myFileStream = new air.FileStream();
myFileStream.open(myFile, air.FileMode.READ);
var myByteArray = new air.ByteArray();
myFileStream.readBytes(myByteArray,0,myFileStream.bytesAvailable);
air.Introspector.Console.log(myByteArray.length);
} else {
alert ('File not found.');
}
var LineNumber;
var ItemCode;
var OrderCode;
var Qty;
var myDir = air.File.documentsDirectory;
var myFile = myDir.resolvePath("Test.txt");
if (myFile.exists) {
var myFileStream = new air.FileStream();
myFileStream.open(myFile, air.FileMode.READ);
var myData = new air.ByteArray();
myFileStream.readBytes(myData,0,myFileStream.bytesAvailable);
var str = myData.toString();
var Pos = 0;
var Tab = 0;
var CRLF = 0;
EOL = str.indexOf("\r",Pos);
while (EOL > 0) {
Tab = str.indexOf('\t',Pos);
LineNumber = str.substring(Pos,Tab);
Pos = Tab + 1;
Tab = str.indexOf('\t',Pos);
ItemCode = str.substring(Pos,Tab);
Pos = Tab + 1;
Tab = str.indexOf('\t',Pos);
OrderCode = str.substring(Pos,Tab);
Pos = Tab + 1;
CRLF = str.indexOf('\r',Pos);
Qty = str.substring(Pos,CRLF);
Pos = EOL+1;
EOL = str.indexOf("\r",Pos);
}
} else {
alert ('File not found.');
}

Categories

Resources