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);
});
Related
I have node.js installed and protractor installed. I have experience with selenium-webdriver but Protractor is driving me nuts!!! I am also not that familiar with javascript.
This is what my code looks like:
describe('My app', function() {
var result = element(by.id('result-name'));
var enterBtn = element(by.id('enter'));
var clearFieldBtn = element(by.id('clear-field');
it('should bring up components on load', function() {
browser.get(`http://localhost:${process.env.PORT}`);
browser.wait(until.titleContains('Sample App'), 500);
browser.wait(until.presenceOf(browser.element(by.id('my-test-app'))), 500);
expect(enterBtn).isPresent;
});
it('result should equal username', function () {
browser.get(`http://localhost:${process.env.PORT}`);
expect(clearFieldBtn).isPresent;
expect(result.getText()).toEqual('John Smith'); //both tests pass without this line of code
});
});
The last line "expect(result.getText()).toEqual('John Smith');" throws me an error. I get:
expect(...).toEqual is not a function
Any help would be much appreciated. I have spent a couple of hours trying to find a solution and trying different things.
I also wanted to implement the isPresent function how it's done in the api docs which is like this: expect($('.item').isPresent()).toBeTruthy();
I tried to do:
expect(clearFieldBtn).isPresent().toBeTruthy();
But I get that isPresent is not a function...
The expect above that line seems poor. It should read
expect(clearFieldBtn.isPresent()).toBeTruthy();
not sure if that is causing the weird error on the line below...just thought I would throw it out there. All your protractor APIs need be be called within the expect because isPresent is not a attribute of expect
Have you tried these lines:
clearFieldBtn.isPresent().then(function(bln) {
expect(bln).toBe(true);
});
result.getText().then(function(tmpText) {
expect(tmpText).toBe('John Smith');
});
If you still get an error on result.getText(), please check the presence of the result object.
I have another question (last question). At the moment i am working on a Node.js project and in this I have many console.log() functions. This has worked okay so far but I also want everything that's written to the console to also be written in a log-file. Can someone please help me?
For example:
Console.log('The value of array position [5] is '+ array[5]);
In my real code its a bit more but this should give you an idea.
Thank you hopefully.
Just run the script in your terminal like this...
node script-file.js > log-file.txt
This tells the shell to write the standard output of the command node script-file.js to your log file instead of the default, which is printing it to the console.
This is called redirection and its very powerful. Say you wanted to write all errors to a separate file...
node script-file.js >log-file.txt 2>error-file.txt
Now all console.log are written to log-file.txt and all console.error are written to error-file.txt
I would use a library instead of re-inventing the wheel. I looked for a log4j-type library on npm, and it came up with https://github.com/nomiddlename/log4js-node
if you want to log to the console and to a file:
var log4js = require('log4js');
log4js.configure({
appenders: [
{ type: 'console' },
{ type: 'file', filename: 'logs/cheese.log', category: 'cheese' }
]
});
now your code can create a new logger with
var logger = log4js.getLogger('cheese');
and use the logger in your code
logger.warn('Cheese is quite smelly.');
logger.info('Cheese is Gouda.');
logger.debug('Cheese is not a food.');
const fs = require('fs');
const myConsole = new console.Console(fs.createWriteStream('./output.txt'));
myConsole.log('hello world');
This will create an output file with all the output which can been triggered through console.log('hello world') inside the console.
This is the easiest way to convert the console.log() output into a text file.`
You could try overriding the built in console.log to do something different.
var originalLog = console.log;
console.log = function(str){
originalLog(str);
// Your extra code
}
However, this places the originalLog into the main scope, so you should try wrapping it in a function. This is called a closure, and you can read more about them here.
(function(){
var originalLog = console.log;
console.log = function(str){
originalLog(str);
// Your extra code
})();
To write files, see this stackoverflow question, and to override console.log even better than the way I showed, see this. Combining these two answers will get you the best possible solution.
Just write your own log function:
function log(message) {
console.log(message);
fs.writeFileSync(...);
}
Then replace all your existing calls to console.log() with log().
#activedecay's answer seems the way to go. However, as of april 30th 2018, I have had trouble with that specific model (node crashed due to the structure of the object passed on to .configure, which seems not to work in the latest version). In spite of that, I've managed to work around an updated solution thanks to nodejs debugging messages...
const myLoggers = require('log4js');
myLoggers.configure({
appenders: { mylogger: { type:"file", filename: "path_to_file/filename" } },
categories: { default: { appenders:["mylogger"], level:"ALL" } }
});
const logger = myLoggers.getLogger("default");
Now if you want to log to said file, you can do it just like activedecay showed you:
logger.warn('Cheese is quite smelly.');
logger.info('Cheese is Gouda.');
logger.debug('Cheese is not a food.');
This however, will not log anything to the console, and since I haven't figured out how to implement multiple appenders in one logger, you can still implement the good old console.log();
PD: I know that this is a somewhat old thread, and that OP's particular problem was already solved, but since I came here for the same purpose, I may as well leave my experience so as to help anyone visiting this thread in the future
Here is simple solution for file logging
#grdon/logger
const logger = require('#grdon/logger')({
defaultLogDirectory : __dirname + "/logs",
})
// ...
logger(someParams, 'logfile.txt')
logger(anotherParams, 'anotherLogFile.log')
I have following long type session on server side code
long[] grouparray = ..;
Session["grouplist"] = grouparray;
Now I'm trying to get this session on View Page's jquery click function
$("#gpline").click(function () {
parseInt(#Session["grouplist"]);
var grouplistvalues = Session["grouplist"];
alert(grouplistvalues);
});
But this is having error once I debug using firebug
SyntaxError: expected expression, got ']'
parseInt(System.Int64[]);
You need to use Json.Encode and #Html.Raw on your c# data to make it compatible with your scripts.
Try this.
$("#gpline").click(function () {
var grouplistvalues = #Html.Raw(Json.Encode(Session["grouplist"])); // converting the session data into array of numbers in javascript variable
alert(JSON.stringify(grouplistvalues)); // stringify is used only to test.
});
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
I have an HTML file thats dynamically generated and only has a javascript object commented out. I'm trying to read that file, take the object out as a string, and run it with VM's runInNewContext(). But I run into a few hurdles.
Heres my code:
The file I have to read:
/*
{
"userId": ["2897599"],
"addressId": ["1287124"]
}
*/
The code I'm trying to use:
var startDataMap = body.indexOf('{')
, endDataMap = body.indexOf('}')
, dataMap = body.substring(startDataMap, endDataMap);
var sandbox = {};
try {
vm.runInNewContext(dataMap, sandbox)
} catch (error) {
console.log(error)
};
If I run this it'll kick back an error of:
[SyntaxError: Unexpected token :]
If I run it with a regex (ie with (/\{/) instead of ('{') ) it will execute without an error but it doesnt catch the data.
Question: Why will neither attempt work and how can I get the data I need using VM?
Update:
I took the advice of the answer below and it removed the error and added a tweak or two. Here is the updated code:
var startDataMap = body.indexOf('{')
, endDataMap = body.indexOf('*/', startDataMap)
, dataMap = body.substring(startDataMap, endDataMap);
var sandbox = {};
try {
vm.runInNewContext( '(' + dataMap + ')', sandbox)
} catch (error) {
console.log(error)
};
It removes the error but sandbox is still empty. I checked dataMap and it does have the required data but there is a line of whitespace at the end. Will this throw VM off? If so, how can I get rid of it, or do I need to alter my endDataMap ?
You likely need to add parentheses, so that the string is interpreted as an object instead of a block:
vm.runInNewContext("(" + dataMap + ")", sandbox)
Curly braces that are not in an expression are treated a blocks. By placing the code inside of parentheses, you make it clear that the code should be an object literal, rather than a block.