I've found a weird behavior with http://underscorejs.org/ in Node JS:
When a reference error happens when we evaluate a template function, Node JS will FREEZE!
Examples:
EXAMPLE 1: HAPPY DAY SCENARIO:
var template = "<%= test %>";
var compiledTemplate = _.template(template);
var result = compiledTemplate({test:1});
console.log(result);
//RESULT (both BROWSER and NODE JS):
//1
EXAMPLE 2: COMPILE ERROR SCENARIO (an extra = before closing):
var template = "<%= test =%>";
var compiledTemplate = _.template(template);
var result = compiledTemplate({test:1});
console.log(result);
//RESULT (both BROWSER and NODE JS):
//uncaughtException { [SyntaxError: Unexpected token )]
EXAMPLE 3: EVALUATION ERROR SCENARIO (test is not defined):
var template = "<%= test %>";
var compiledTemplate = _.template(template);
var result = compiledTemplate({no_test_defined:1});
console.log(result);
//RESULT (BROWSER):
//Uncaught ReferenceError: test is not defined
//RESULT (NODE JS):
//Node JS FREEZES - nothing happens, neither and error is thrown, neither the flow goes on
Anybody had ever get a similar behavior? Any hints for solution? I really need to catch the exception in a try/catch block...
Cheers!
Oscar
After some troubleshoot I could finally found what was the problem.
When I run this inside Webstorm DEBUGGER, this behavior happens (Node JS FREEZES). When I run it in command line, i works as expected. I will search in Webstorm issues if hey have something.
Cheers!!!!
Oscar
Related
Chutzpah and Jasmine runs fine in my solution in Visual Studio, for my javascript tests.
I have an issue, and I think it's chutzpah but I'm not 100% certain (it could be Jasmine).
I now need to test my extension methods, which contains code similar to
if (!Array.prototype.where) {
Array.prototype.where = function(callback) {
const arr = [];
this.forEach(function(item) {
if (callback(item)) {
arr.push(item);
}
});
return arr;
};
}
My Jasmine test is.
//arrange
const array = [];
const fixedInput = "a";
array.push(fixedInput);
array.push("b");
//act
const result = array.where(a => a === fixedInput);
//console.log(result);
//assert
const expected = [fixedInput];
expect(result).toBe(expected);
expect(result.length).toBe(1);
I am unable to run this test, over command line or the Chutzpah plug in within Visual Studio (and it does not show as a viable test in VS)
If I comment out the const result = array.where(a => a === fixedInput); then the test is discovered.
If I execute the test, with that line commented out, the Jasmine web page of test results is shown - with it open, I can edit the test, uncomment the line and I get the result I would expect (but only for a few seconds until that result page turns into a "file not found").
The output window shows
Unknown error occurred when executing test file. Received exit code of 2
I don't know how to solve this. Any advice?
You are probably hitting an issue that Chutzpah by default uses an old JS engine. You should configure your chutzpah.json to use a newer one https://github.com/mmanela/chutzpah/wiki/Browser-Engines
I have the following script (script.js):
categoricalVars = db.frekvencija_ctg.find().toArray();
db.ctg.find().forEach(e => {
db.emb_ctg.insert({ ...e, frekvencija: categoricalVars });
});
When I try to load it in Mongo shell via load("script.js"), I get the following error:
[js] SyntaxError: illegal character :
If I run these expressions in Mongo shell one by one with copy/paste, they work and I get desired result. What is wrong in script?
Seems like you're using an old version of node that doesn't support fancy syntax. Either udgrade node or use old school syntax like :
var categoricalVars = db.frekvencija_ctg.find().toArray();
db.ctg.find().forEach(function(e){
db.emb_ctg.insert(Object.assign({},e, {frekvencija: categoricalVars }));
});
I have got this error before and I have resolved this by removing the braces from the arrow function passed to the forEach() method.
Try changing your script to something like this
categoricalVars = db.frekvencija_ctg.find().toArray();
db.ctg.find().forEach(function(e){
var obj = {...e};
obj.frekvencija = categoricalVars;
db.emb_ctg.insert(obj);
});
I am creating a package in node to parse and manipulate csv and needed to use String.matchAll() and I got an error saying str.matchAll is not a function. I tried switching to str.match() and got the same error. I tried to console.log each and both returned undefined. I typed node -v into the visual studio code powershell and it spat out v10.16.3
my code
fs = require('fs');
class Table {
//the function I needed it for
removeRow(header, value){
let regLine = "";
for(let i=0; i<this.colArr.length; i++){
if (this.colArr[i][0]==header){
regLine+=value+",";
}else{
regLine+=".*,"
}
}
regLine = "\n"+regLine.substring(0,regLine.length-2)+"\n";
let regex = new RegExp(regLine);
let removed = this.text.matchAll(regex);//this line
let newText = this.text.replace(regex,"\n");
fs.writeFile(this.link, newText);
this.update();
return removed;
}
}
At the line marked it throws the error this.text is not a function I console.logged typeof(this.text) and it gave string so I don't know whats going on
String.matchAll is only available from Node.js 12.0 onwards (see compatibility here: string.matchAll).
String.match however should be available from early versions of Node.js.
Here's an example I've created of it in action (Node v10.16.0): https://repl.it/repls/PunctualRareHypotenuse
I'd suggest also ensuring that the object in question is a string just to be sure!
Also if it's easy for you to upgrade, try installing Node.js 12.
Code:
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/g;
var matches_array = str.match(regexp);
console.log(matches_array);
I have hit a problem that seems like it might be some sort of bug in the Nashorn engine, but I can't figure out a good way to distill a test case that will demonstrate it.
I have a block of code (that used to work!) which looks roughly like this:
'use strict';
function Dummy() {
this.val = 'I am fubar';
this.aContainer = [];
}
Dummy.prototype.toString = function() { return JSON.stringify(this);};
let obj = {};
obj.aMethod = function(arg) {
let fubar = new Dummy();
print('Okay so far');
fubar.aContainer.push({"some":"thing"});
print('Still okay');
fubar.aContainer.push({"==": [{"var": "something_else"}, fubar.val]});
return fubar;
};
print(obj.aMethod(null));
Unfortunately, running this example with jss --language=es6 -strict doesn't crash. In my real code though, I get the following:
jdk.nashorn.internal.runtime.ECMAException: ReferenceError: "fubar" is not defined
If I change the code as follows, it runs fine:
'use strict';
function Dummy() {
this.val = 'I am fubar';
this.aContainer = [];
}
Dummy.prototype.toString = function() { return JSON.stringify(this);};
let obj = {};
obj.aMethod = function(arg) {
let fubar = new Dummy();
print('Okay so far');
fubar.aContainer.push({"some":"thing"});
print('Still okay');
let x = fubar.val;
fubar.aContainer.push({"==": [{"var": "something_else"}, x]});
return fubar;
};
print(obj.aMethod(null));
Is there anything I can do to try to instrument the real code further or otherwise track this issue down? The odd thing is the error happens very early in execution. If I put a print() call anywhere in the method, the print is never reached. The last line of my code in the callstack is actually the line that calls the method.
I did just pick up a new version of Java via auto-update, but I need to see if this code is running under it or not. My current version from the console is:
➜ ~ java -version
java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)
A full summary of all you can do to trace Nashorn is contained in this document:
jdk8u-dev/nashorn/file/tip/docs/DEVELOPER_README
It describes system properties that are used for internal debugging and instrumentation purposes, along with the system loggers, which are used for the same thing.
This question already has answers here:
Underscore template throwing variable not defined error
(2 answers)
Closed 7 years ago.
I try to pass data immediately to template call:
var compiled = _.template('template code there', {params: 123})
And regards to specs the variable 'compiled' must be ready to use as HTML markup.
But! I got a function..
It's really strange for me.. I ran this code at plnkr.co, and it gave expecting result, but locally it's not working as expected.
p.s. In my example I use bower to download scripts
<script src="../scripts/vendor/jquery/dist/jquery.js"></script>
<script src="../scripts/vendor/underscore/underscore.js"></script>
<script src="../scripts/vendor/backbone/backbone.js"></script>
...
var list = "<%= ... %>";
var compiled = _.template(list, {data : ['one', 'two']});
alert(compiled); // got function !
Can anybody explain this?
P.S. worked example - http://jsfiddle.net/xm6ymxoj/
and I can't reproduce this simple code locally on my machine, as result I receive a function (in alert).
_.template(templateString, [settings]) (see docs) compiles a string to a template. This template is a function that can then be rendered to HTML with some given data.
From the docs:
var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"
EDIT: So in your example you should use:
var list = "<%= ... %>";
var compiled = _.template(list);
var html = compiled({data: ['one', 'two']})
It's many code examples in network something like this one:
var c_markup = _.template("Hello <%=user%>!", { user: "MyName" });
But as I understand this code is obsolete, and not worked now.
We need to pass parameters to prepared function call:
var c_markup = _.template("Hello <%=user%>!");
c_markup({ user: "MyName" });
This moment was confused me. Hope this can helps someone.