Coder Social home page Coder Social logo

steveorevo / node-red-contrib-string Goto Github PK

View Code? Open in Web Editor NEW
21.0 4.0 2.0 361 KB

Provides a string manipulation node with a chainable UI based on the concise and lightweight stringjs.com.

HTML 90.56% JavaScript 9.44%
string-manipulation string-matching parse string

node-red-contrib-string's Introduction

node-red-contrib-string

Provides a node with native and extended chainable JavaScript string parsing and manipulation methods. The node is a high level wrapper for the concise and lightweight stringjs.com object and uses Node-RED's editor UI to create easy chaining. Additional string parsing functionality and compatibility have been added from the fork.

Applies string methods from a given context property and assigns the results optionally to the same or another context property. Methods can be chained by adding multiple methods sequentially and with parameters that are literal or from other context properties. The string object always passes along the msg object with (if any) changes applied.

By default, string "from" and "to" apply to the msg.payload property but may be set to any property of global, flow, or msg contexts.

Examples

Data Extraction - Get Technical FAX

Methods can be chained within the UI enabling complex and versatile parsing functionality. Here we can see how easy it is to extract the technical FAX phone number WhoIS information:

Node-RED Example

Consider the given WhoIS dump from a command line console (see image below). We will want to obtain the FAX number (outlined in the dashed yellow). The string node will extract the technical FAX phone number by first removing the header, followed by all data up to the phrase "Technical:". This ensures that we don't accidentally obtain a FAX number from another section. Lastly, the string node grabs the number from between the markers "Fax:" and a carriage return and displays the output in the Node-RED debug window.

WhoIS Commandline Dump

The extraction is performed using JavaScript's unique ability to chain actions on a given object such as the native String object or the popular jQuery component. This unique contribution to Node-RED furnishes a lightweight and enhanced version of string parsing functions. The visual representation in the first image could be coded by hand in JavaScript (after including all the dependencies) as:

console.log(
  msg.payload.getRightMost('%')
             .delLeftMost('Technical:')
             .between('FAX:', '\n')
);

Validate Phone Number

Furthermore, a single string node could have the properties set to perform data validation. In this simple example we'll perform some conditional checks to see if the phone number is numeric and furnish a friendly error message if it is not. Consider the following flow:

Validate Phone Number

Let's take a look at the string node titled "Verify Number" (see image below). The properties for the node have been configured to use the methods stripPunctuation and isNumeric which will result in a boolean true or false. Next, we convert the boolean to a string using toString. Lastly, we use the replaceAll methods to convert the only two boolean possibilities to the original number as found in property msg.payload or the informative error message "Error! Not a valid number.".

Verify Number Node

Using String in Node-RED Function Nodes

You can use the string object's methods inside Node-RED's function nodes. The dependency string.js for Node.js will have already been installed if you included the string node in your palette. This would allow you to use the parsing methods in JavaScript such as:

  // Always change the last word to World
  var greet = S("Hello Mars");
  msg.payload = greet.delRightMost(" ").append("World");

There are several easy ways to make the string object's methods available in your JavaScript function nodes:

Include String Node in Flow

A simple way is to just include the string node in your flow before the Node-RED function node. The string node will normally return a native JavaScript string datatype; however, if you use the setValue method with no value, a string.js object can be casted into a readily available property. In our example below we cast the object into msg.string.

Using String in JavaScript

The string object returns an instance of itself when using the setValue method. You can then write JavaScript to instantiate a copy of the string object.

var S = function(x) {
  return msg.string.setValue(x);
}
msg.payload = S("Hello World");

Enable Require in Node-RED

An alternative method to use the string object is to enable the require method by updating Node-RED's settings.js to enable Node.js' "require" ability.

node-red/node-red#41 (comment)

functionGlobalContext: {
    require:require,
    // os:require('os'),
    // octalbonescript:require('octalbonescript'),
    // jfive:require("johnny-five"),
    // j5board:require("johnny-five").Board({repl:false})
},

This will essentially give Node-RED's function node the ability to include any arbitrary Node.js library which you may or may not desire. Likewise, you could just update Node-RED's settings.js to just enable the string.js library by modifying the functionGlobalContext to read:

functionGlobalContext: {
    string:require("string")
},

Your Node-RED's function node could then instantiate a string object like so:

var S = global.get("string");
msg.payload = S("Hello World");

Installation

Run the following command in your Node-RED user directory (typically ~/.node-red):

npm install node-red-contrib-string

The string node will appear in the palette under the function group.

node-red-contrib-string's People

Contributors

steveorevo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

beosro alexrzem

node-red-contrib-string's Issues

Cases

Is it possible to have other CASE options like upper case, lower case and title case?

Thank you.

Installation instructions issue

"Run the following command in the root directory of your Node-RED install"

Should be "Run the following command in the user directory of your Node-RED install"

You shouldn't install nodes as the root user unless you really have to and Node-RED should never need that.

Remove accents

Hello.
Is it possible to remove accents like : é è ç ' etc

Thank you.
Marc.

Extract each indivisible characters from a string.

Hi,

Using node-red I have extracted a 15 digit string "100121001000111" that I need to break out /mdiwn individually I order to translate each one, as each byte means something.

So farm I can’t take the furthest left or right character, but I can seem to work out how to take the the 2nd or 3rd from left or fourth or fifth from right etc.?

GetxxxxMost, DelxxxMost without losing searched keyword

Hi,
Thanks for your useful node !
I don’t think it’s a bug, but rather a request.
I have noticed that all these commands DelLeftMost, DelRightMode, GetRightMode, GetLeftMode will lose the searched keyword.

Here a portion of my sample to parse :
..."Sleep":50,"LoadAvg":19,"POWER1":"ON","POWER2":"OFF","POWER3":"ON","POWER4":"OFF","Wifi":"mywifi" ....

At first I would like to extract this part : POWER1":"ON","POWER2":"OFF","POWER3":"ON","POWER4":"OFF"

The problem:
If I use command like DelLeftMost POWER, because the searched keyword is lost I get this :
1":"ON","POWER2":"OFF","POWER3":"ON","POWER4":"OFF","Wifi":...
For the right part in this case that’s ok to lose the keyword DelRigthMost Wifi
Note that the string haven’t a fixed length, so I cannot extract just a length.

I think I have tried all commands without success, but maybe I have missed something

Thank you

I have tried a lot of commands available without success but maybe I have missed something

How is it supposed to work?

I want to modify the msg.payload (a string) depending on its contents. If I try to use anything that modifies the string, as opposed to testing it, I get

"TypeError: Cannot read properties of undefined (reading 'apply')"

What does the documentation mean when it mentions 'a given context property'? I see no way to set one

Wrong link?

In your documentation the link to stringjs.com is mentioned.

I don't think it is still valid.

decodeURIComponent producing "URIError: URI malformed"

I'm trying to decode "70%20%", which some tools correctly recognise as "70 %", but others fail to decode, like this does. I have a workaround, but it would be good to have it cope.

I have an IFTTT applet calling Bluemix with a webhook. When I speak "70 %" to my Google Home, and it gets passed through IFTTT to Node-Red, it arrives as "70%20%", so I'm guessing that IFTTT's encode is causing the problem.

A sample flow showing the problem:

[{"id":"4d881eee.0ad06","type":"string","z":"f6747993.c9b448","name":"","methods":[{"name":"decodeURIComponent","params":[]}],"prop":"payload","propout":"payload","object":"msg","objectout":"msg","x":340,"y":460,"wires":[["bd547a18.09bc38"]]},{"id":"8ff76890.de6ce8","type":"inject","z":"f6747993.c9b448","name":"","topic":"","payload":"70%20%","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":180,"y":460,"wires":[["4d881eee.0ad06"]]},{"id":"bd547a18.09bc38","type":"debug","z":"f6747993.c9b448","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":500,"y":460,"wires":[]}]

In OSX, nothing is showing in the methods section

8 Dec 06:59:41 - [info] Node-RED version: v0.17.5
8 Dec 06:59:41 - [info] Node.js version: v6.11.0
8 Dec 06:59:41 - [info] Darwin 16.7.0 x64 LE

After installing the node, and opening an occurrence there is nothing in the Methods section, it is blank
screen shot 2017-12-08 at 7 04 29 am

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.