Using String.raw() with Node JS - javascript

I'm working on a Node.js app with and I would like to use String.raw() which is part of the ES 6 standard.
However, when using it as in the documentation:
text = String.raw`Hi\n${2+3}!` + text.slice(2);
It returns SyntaxError: Unexpected token ILLEGAL for the character after String.raw.
I think that there is a problem because String.raw() is a new technology only available for Chrome and Firefox yet. However, can I use it in Node.js and how?

The grave character after raw denotes template strings, which is a feature in ES6 Harmony. You can invoke node with --harmony flag, but this feature is not yet implemented. This is the reason of the syntax error. Raw strings are unsupported too.
If you want experimenting with this feature in server side, check out io.js, which is a fork of node, but with many ES6 features implemented and enabled by default.

Related

Can we use Buffer.from in typescript frontend code

Can we use Buffer.from to Base 64 encode a string in a front end typescript application. Using btoa() is showing as deprecated.
No you cannot. Buffer is a Node.js specific class and it does not exist in browsers.
The warning is beacause you have node types in your proyect, so Typescript Compiler thinks that you're using atob in node (which is totally deprecated) but you don't. You are totally fine using atob in front-end.
To solve the warning you can remove node types (if you're not using them), or to make it simple, a comentary before your atob call should be enought to avoid any warning from the next line:
// #ts-ignore
Your atob call goes here
Make sure you keep it simple under the #ts-ignore, you don't want to hidde a real problem there.

Path separator for Atom / JavaScript on Windows

I have developed an Atom package which calls SyncTeX (a utility for reverse lookup for LaTeX), and then opens in Atom the file specified in the SyncTeX response. I'm developing on Linux, but now a user on Windows tells me that this doesn't work.
In detail: SyncTeX returns a pathname like C:\data\tex\main.tex, with Windows-appropriate backslash separators. My package then calls atom.workspace.open with exactly that returned string, which leads to a JavaScript error (file not found).
Strangely, if the string is modified to use forward slashes instead, C:/data/tex/main.tex, the call works and the file is opened.
My questions:
Is this behavior specific to Atom, or to some underlying technology (JavaScript, Electron, Node, ...)? I was unable to find any documentation on this.
Since the replacement \ → / is apparently necessary, is there a preferred way to implement it? Would a simple String.replace be adequate?
Do I risk breaking compatibility with other platforms if I always do the replacement?
By my best knowledge paths with forward slashes '/' work well everywhere except Windows XP.

Unicode regex \p{L} not working in NodeJS

I am trying to make the following unicode regular expression work in nodejs, but all I get is an invalid escape error. I can't figure out, what to escape here or if this for some reason doesn't work at all in node. This is my original regex:
/([\p{L}|\-]+)/ug
If I escape the \p like \\p, the regex doesn't work anymore (outputs only p,L and -)
This works in chrome, so it should work in node somehow too, right? Thanks for your help.
var str = "thÛs Ís spå-rtÅ!";
console.log(str.match(/([\p{L}|\-]+)/ug))
A quick look through the nodejs changelog revealed this PR:
https://github.com/nodejs/node/pull/19052
which most notably states:
RegExp Unicode Property Escapes are at stage 4 and will be included in ES2018. They are available since V8 6.4 without a flag so they will be unflagged in Node.js v10. They are also available under the --harmony_regexp_property flag in Node.js v6-v9 and under the --harmony flag in Node.js v8-v9.
So by the look of it, if you are on node v6-v9, you can enable this feature by running node with a flag. For example, this works for me on node v8.11.3:
node --harmony regex-test.js
(where regex-test.js contains your sample code). Running this without the flag gives your Invalid escape error.
If you can update your node version to v10+, no flag is needed.
If you are going to use --harmony flag please consider this
As mentioned in the Node Documentation, --harmony flag enables the non-stable but to be soon stable features of ES6
The current behaviour of the --harmony flag on Node.js is to enable staged features only. After all, it is now a synonym of --es_staging. As mentioned above, these are completed features that have not been considered stable yet. If you want to play safe, especially on production environments, consider removing this runtime flag until it ships by default on V8 and, consequently, on Node.js. If you keep this enabled, you should be prepared for further Node.js upgrades to break your code if V8 changes their semantics to more closely follow the standard.
here is the link for that
https://nodejs.org/en/docs/es6/#:~:text=The%20current%20behaviour%20of%20the,to%20enable%20staged%20features%20only.&text=If%20you%20want%20to%20play,js.

Using regexp namespace from EXSLT in browser console causes a SyntaxError

I want to use regexp namespace in my XPath expressions when searching elements in browser console, but get SyntaxError: The expression is not a legal expression. trying to do so.
I followed http://help.dottoro.com/ljspsvcs.php as a tutorial for creating a namespace resolver.
Here's my code:
function nsResolver (nsPrefix) {
if (nsPrefix == "regexp") {
return "http://exslt.org/regular-expressions";
}
return null;
}
document.evaluate('//a[regexp:test(#href, "qwerty-[\d]+$")]', document.documentElement, nsResolver, XPathResult.ANY_TYPE, null);
What am I doing wrong here?
The fact that someone has defined a set of extension functions in a particular namespace does not mean that every XSLT processor supports those functions. What is wrong here is that you are using an ancient XSLT processor that has not been upgraded in years (because the browser vendors lost interest in the XML user community).
Consider installing Saxon-JS, which provides XSLT 3.0 running in the browser, with built-in regular expression support according to W3C specifications. (Disclaimer: it's my company's product).

Checking if code is valid JavaScript without actually evaluating it

Is there a function to test if a snippet is valid JavaScript without actually evaluating it? That is, the equivalent of
function validate(code){
try { eval(code); }
catch(err) { return false; }
return true;
};
without side effects.
Yes, there is.
new Function(code);
throws a SyntaxError if code isn't valid Javascript. (ECMA-262, edition 5.1, §15.3.2.1 guarantees that it will throw an exception if code isn't parsable).
Notice: this snippet only checks syntax validity. Code can still throw exceptions because of undefined references, for example. It is a way harder to check it: you either should evaluate code (and get all its side effects) or parse code and emulate its execution (that is write a JS virtual machine in JS).
You could use esprima.
Esprima (esprima.org) is a high performance, standard-compliant ECMAScript parser written in ECMAScript (also popularly known as JavaScript).
Features
Full support for ECMAScript 5.1 (ECMA-262)
Sensible syntax tree format, compatible with Mozilla Parser AST
Heavily tested (> 550 unit tests with solid 100% statement coverage)
Optional tracking of syntax node location (index-based and line-column)
Experimental support for ES6/Harmony (module, class, destructuring, ...)
You can use the online syntax validator or install it as npm package and run it locally from the command line. There are two commands: esparse and esvalidate. esvalidate yields (given the example from the online syntax validator above):
$ esvalidate foo.js
foo.js:1: Illegal return statement
foo.js:7: Octal literals are not allowed in strict mode.
foo.js:10: Duplicate data property in object literal not allowed in strict mode
foo.js:10: Strict mode code may not include a with statement
For the sake of completeness esparse produces an AST.

Categories