Node-Red JavaScript Reference Manual

Hello,
Being somewhat new to Node-Red, and in particular JavaScript. Node-Red JavaScript appears to be a subset of standard JavaScript; is there a reference manual for JavaScript as it relates to Node-Red.

For instance, I have found that semi-colon's are not required, haven't checked braces yet. Also, indenting for conditionals does not appear to be a requirement either. I assume there are many standard JavaScript constructs that would not be compatible with a Function-Node.

semi colons are not required in standard JavaScript

braces are not required if there is only 1 instruction following the if or while or for - again, standard JavaScript

indentation means nothing to JavaScript (its not python) - this is standard JavaScript


The JavaScript node-red uses in the function node may seem somewhat restricted however that is because it runs in nodejs (server side) NOT a browser (i.e. the window object is not available in the function node)

Node-RED JavaScript is just JavaScript. It isn't a special version.

We provide some built-in objects, as listed in the docs on nodered.org, but the language itself is regular JavaScript.

Semicolons are not required in JavaScript. It is one of those tab-vs-spaces type of debates where different developers prefer different styles.

But ultimately, it's just JavaScript

The only reason I mentioned semi-colons, and braces, etc. because a recent book I purchased on standard JavaScript only has examples of JavaScript with those constructs.

Thanks for the reply, but it would be useful if there were a Node-Red JavaScript reference manual as it relates to Function-Node compatibility; it would save a lot of experimentation.

Sounds like I need a better standard JavaScript book - lol

True enough, but then again Python never requires braces. :slightly_smiling_face:

I have my own opinions on paper books for languages as dynamic as JavaScript :grimacing:

If you study examples of JS you will find that many people have given up on semi-colons and indeed there is a style guide for JS called "standard" which is used by many large projects that explicitly excludes them.

Brackets are perhaps a little different, though in fact "standard" style does require you to include them even when not strictly required.

There is nothing special about the JS in a function node at all. However, three points need to be remembered:

  1. The function node uses the node.js flavour of JS as already noted. Typically this is actually often ahead in the versions of JS than browsers tend to be.
  2. The code in a function node runs in node.js's "VM" (Virtual Machine) which applies a few limitations. Documentation is provided by the node.js project.
  3. Function node code inherits some additional special node-red objects. These are somewhat highlighted by the editor and are documented in the node-red docs.

I am, however certain that if you were to contribute some additional documentation in the style of the existing docs, this would be well received since there are never enough contributors to documentation.

Forget the books. New major releases of JS are currently happening each year. Books are out of date well before they are published.

Instead, go have a deep browse through the amazing resources that constitute the Mozilla Developer Network (MDN).

But if you confuse spaces and tabs it dies horribly quite often! :frowning:

Python has its fair share of structural and versioning issues as well. So generally best to avoid poking the bear that is a language war :smiley:

1 Like

It does indeed, a major stumbling block for beginners!

First, thank you for your detailed and professional response.

I only reference Python, because Steve-Mcl put a hit on it first.

Regarding semi-colons; I've done a little more reading on the subject, and indeed they are not required. They are only considered "good practice", however some IDE's require them and will throw an error if not included.

Again, thanks for the detailed response.

:smiley:

Actually not so much now. As I say, many large and small projects have long dropped them. I personally never use them and haven't for some years.

Really? Which?

A lot of people have now switched to VScode (even Node-RED which now uses the web Monaco version). Typically, it is wise to dev JS in VScode with the help of the ESLINT extension. ESLINT has a number of templates available that helps you standardise your code. All of my JS code uses JS Standard style with a couple of small modifications to make it slightly less strict as I'm just too lazy an old dog to both adapting. :rofl:

Here, for example, is my .eslintrc.js config file for uibuilder's node code (I have modified versions to work with browser-based code).

/** JavaScript Versions
 *  5 is minimum -> Last IE11
 *  6 = 2015 -> Node >8.10, iOS12+
 *  7 = 2016 -> FF78+,
 *  8 = 2017 -> Node 10.9+
 *  9 = 2018 -> Node 12.11+
 * 10 = 2019 -> Node 12.20 LTS
 * 11 = 2020 -> Node 14 LTS
 * 12 = 2021 -> Node 16
 */
/** Node.js supports (https://node.green/):
 * v07 - async/await
 * v09 - tagged template literals with invalid escape sequences,  RegExp lookbehind assertions
 * v10 - optional catch binding (no need for err param on catch), BigInt, import.meta,
 *         RegExp Unicode property escape sequences \p{...},
 *         trimStart/trimEnd, async iteration, Promise.prototype.finally,
 *         RegExp named capture groups
 * v11 - Array.prototype.{flat,flatMap}, Symbol.prototype.description
 * v12 - Promise.allSettled, globalThis, numeric separators, Object.fromEntries
 * v13 - import (modules), dynamic import(), export
 * v14 - optional chaining, Nullish Coalescing operators, String.prototype.matchAll,
 *         Intl.DisplayNames, Intl.DateTimeFormat, (Experimental: Async Local Storage, Top-Level Await, Diagnostic report),
 *         WeakReferences, private class methods
 * v15 - logical assignment operators, String.prototype.replaceAll, Promise.any, AggregateError, AbortController,
 *        Promisified setTimeout/setImmediate
 */
module.exports = {
    env: {
        browser: false,
        commonjs: true,
        jquery: false,
        node: true,
        // es2019: true,
        'shared-node-browser': false
    },
    parserOptions: {
        // Only ESLint 6.2.0 and later support ES2020. Node.js v12+ supports some things only ratified in 2020
        'ecmaVersion': 2022,
        sourceType: 'script'
    },
    root: true,
    globals: {
        Set: true, // Not sure why eslint doesn't recognise this as it is part of node.js since v0.12
        RED: true,
    },
    overrides: [
        {
            files: ['*.module.js', '*.mod.js', '*.mjs'],
            parserOptions: { sourceType: 'module' },
        }
    ],
    plugins: [
        'html',     // Check scripts in HTML. https://www.npmjs.com/package/eslint-plugin-html
        'es',       // Help avoid js that is too new. https://eslint-plugin-es.mysticatea.dev/
        'jsdoc',    // JSDoc. https://www.npmjs.com/package/eslint-plugin-jsdoc
        'promise',  // Better promises. https://www.npmjs.com/package/eslint-plugin-promise
        'sonarjs',  // Detect bugs and suspicious patterns. https://github.com/SonarSource/eslint-plugin-sonarjs
        // 'prettier', // https://www.npmjs.com/package/eslint-plugin-prettier
        // 'eslint-plugin-n', // loads itself from extends, no need to manually load
    ],
    extends: [
        'standard',
        // 'eslint:recommended',
        'plugin:es/restrict-to-es2019',
        'plugin:jsdoc/recommended',
        'plugin:promise/recommended',
        'plugin:sonarjs/recommended',
        // 'plugin:prettier/recommended',
        // The n plugin reads the min. node.js version from package.json and error's any ES features not available in that version.
        'plugin:n/recommended',
    ],
    // settings: {
    //     jsdoc: {
    //         mode: 'permissive'
    //     }
    // },
    rules: {
        'n/no-process-exit': 'error',

        // remove once min engines moves to node.js v14+
        'es/no-optional-chaining': 'error',
        'es/no-dynamic-import': 'error',
        'es/no-nullish-coalescing-operators': 'error',
        // remove once min engines moves to node.js v15+
        'es/no-logical-assignment-operators': 'error',
        'es/no-promise-any': 'error',
        'es/no-numeric-separators': 'error',

        // Tidy up some jsdoc oddities
        'jsdoc/multiline-blocks': 0,
        'jsdoc/newline-after-description': 0,
        'jsdoc/no-multi-asterisks': 0,
        'jsdoc/tag-lines': 0,
        'jsdoc/valid-types': 0, // Rubbish, fails on common type configs
        'jsdoc/no-undefined-types': 0, // ['error'|'warn', {'definedTypes':['Promise']}],

        // Try to keep code complexity in functions to a minimum
        'sonarjs/cognitive-complexity': ['error', 60],  // default is 15! Need to try and improve this :-)

        // Make Standard less annoying
        'brace-style': 'off',     // You should only use one-true-brace style but sometimes we want to compress things a bit.
        'comma-dangle': 'off',    // Lack of dangles wastes soo much time correcting lists
        'dot-notation': 'off',    // Turn off to allow for tslint's brain-dead treatment of expando objects in JS
        'indent': ['error', 4, { 'SwitchCase': 1 }],   // Standard wants 2, I like 4
        'space-before-function-paren': 'off', // No, don't need space between fn and arg!
        'no-multi-spaces': 'off', // Readability is more important than size (reduce size using uglify)
        'object-shorthand': ['error', 'consistent'],
        'padded-blocks': 'off',   // Sometimes you just need some space! See above.
        'space-in-parens': 'off', // Sometimes you just need some space!
        'spaced-comment': ['error', 'always', {
            'markers': ['html', '#region', '#endregion']
        }],
        'quote-props': 'off',     // Sometimes it is necessary and then much nicer to be able to quote things that don't need it.
    }
}
1 Like

I don't recall the specific IDE's, however this is the book I was thumbing thru in Barnes & Noble this afternoon that mentioned "good practice" and the specific IDE's.
https://www.barnesandnoble.com/w/murachs-javascript-and-jquery-mary-delamater/1125476435?ean=9781943872626

Hmm, well that kind of proves my point about paper books on JavaScript I think :rofl:

4th edition in 2020, I wonder how much it really tracks current thinking? Of course, I'm not a pro JS developer so maybe I'm just spouting off. I do have an old JS book on my shelf but I've not even opened it in decades. So much easier to look things up online - which I have to do constantly because I don't use JS every single day and at 62 I fear my memory in some areas not quite as good as it used to be.

Given the time it takes to write a technical book, particularly Murach's tome, they're generally obsolete when they hit the shelves.

1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.