How to save and execute script as function in MongoDB? - javascript

In each deploy of our system, we have some mongodb scripts that we run in NoSQL Manager via Shell.
By running the scripts remotely, they have performance issues when we need to use cursors.
Is it possible to save a script as a function in mongo and run it calling via shell?
I managed to save it as a function, but when I run it, an error similar to the following error occurs:
// Command #1 1:1 0,007 s
uncaught exception: SyntaxError: unexpected token: identifier :
DB.prototype.loadServerScripts/<#src/mongo/shell/db.js:1310:29
DBQuery.prototype.forEach#src/mongo/shell/query.js:512:9
DB.prototype.loadServerScripts#src/mongo/shell/db.js:1308:5
#(shell):1:1
// Command #2 2:1 0,003 s
uncaught exception: ReferenceError: findProductFunctionTest is not defined :
#(shell):1:1
enter image description here
Performed step by step:
Save the script as a function:
db.system.js.insertOne(
{
_id: "findProductFunctionTest",
value : function()
{
try
{
var produto = db.Produto.findOne({Nome: /como treinar/i});
if (produto == null)
throw new Error("Produto não encontrado!");
return produto.Nome;
}
catch (ex)
{
printjson("Erro ao processar! Exceção: " + ex.message);
}
}
}
);
Load script from local server, via shell command:
db.loadServerScripts();
Call function, via shell command:
findProductFunctionTest();

Related

Prevent Unexpected end of file error from halting code execution

My code uses the npm unzipper package to unzip a file into its separate entries and write each individual entry into memory. My code looks like this:
const zipFileEntries = fs.createReadStream(zipFilePath).pipe(unzipper.Parse({ forceStream: true }));
for await (const entry of productFeedsZip) {
try {
// for reference: entry.path returns the file name
entry.pipe(fs.createWriteStream(`/entry/write/path/${entry.path}`));
// ERROR OCCURS HERE AT AUTODRAIN
entry.autodrain();
} catch (err) {
console.log(err)
continue;
}
The .zip file I am reading from changes daily and I read from it upon changing. The issue is that sometimes the .zip file contains a faulty file (something that is out of my control) that causes the following error:
Error: unexpected end of file
at Zlib.zlibOnError [as onerror] (node:zlib:189:17) {
errno: -5,
code: 'Z_BUF_ERROR'
}
All I am looking to do is make it so that when my code encounters this error, the program execution is not halted and the for loop will continue onwards and write the next file entry into storage.
As you can see, I attempted a solution by inserting a try/catch block inside of the for loop, but this does not prevent program execution from halting when it encounters this error.
Anyone know how I can handle this error and allow my for loop to continue iterating over the .zip file entries?

How to run a CMD on web assembly without a server

I wanted to create a web assembly program that would enable me to execute bash commands and get output without contacting a server.
I created some rust code and did a wasm-pack compiling but it gives this error
RuntimeError: unreachable executed
My code
use std::process::Output;
use wasm_bindgen::prelude::*;
use std::process::Command;
#[wasm_bindgen]
pub fn exec(code:&str)->Vec<u8>{
let output = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(["/C", code])
.output()
.expect("failed to execute process")
} else {
Command::new("sh")
.arg("-c")
.arg(code)
.output()
.expect("failed to execute process")
};
output.stdout
}
^^lib.rs (used wasm-pack)
RuntimeError: unreachable executed

After loading two javascript files in jmeter I am unable to use the functions of javascript files

I am using jmeter version 5.2.1. For loading my javascript file I am using jsr223 sampler with language as javascript.
My problem is that I have to login on cognito from jmeter without using external phantomjs driver. So I have imported the cognito javascript files that are used for login on cognito and provided the correct details. Previously this code was working correctly when I was login using phantom js through external created js files. But on moving my code in jsr223 sampler it is giving error "AWSCognito" is not defined in .
I have also increased the size of jsr223 sampler to 600 i.e
jsr223.compiled_scripts_cache_size=600
I am executing the following code
load("D:/apache-jmeter-5.2.1/bin/aws-cognito-sdk.min.js");
load("D:/apache-jmeter-5.2.1/bin/amazon-cognito-identity.min.js");
//var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
var userData = { user_email: 'test#test.com', user_pw: 'test', UserPoolId: 'test', ClientId: 'test',}
var authenticationData = {
Username : userData.user_email,
Password : userData.user_pw,
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId : userData.UserPoolId,
ClientId : userData.ClientId
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var userData = {
Username : userData.user_email,
Pool : userPool
};
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
// console.log('access token + ' + result.getAccessToken().getJwtToken());
//document.getElementById("successAndErrorMessages").innerHTML=result.getAccessToken().getJwtToken();
log.info(result.getAccessToken().getJwtToken());
},
onFailure: function(err) {
log.info(err);
},
});
on executing my script I got the following error
2020-01-02 10:47:59,037 INFO o.a.j.t.ThreadGroup: Started thread group number 1
2020-01-02 10:47:59,038 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started
2020-01-02 10:47:59,039 INFO o.a.j.t.JMeterThread: Thread started: AutomationR&D 1-1
2020-01-02 10:48:00,381 ERROR o.a.j.p.j.s.JSR223Sampler: Problem in JSR223 script JSR223 Sampler (load js)path, message: javax.script.ScriptException: ReferenceError: "AWSCognito" is not defined in <eval> at line number 15
javax.script.ScriptException: ReferenceError: "AWSCognito" is not defined in <eval> at line number 15
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470) ~[nashorn.jar:?]
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:454) ~[nashorn.jar:?]
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406) ~[nashorn.jar:?]
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402) ~[nashorn.jar:?]
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155) ~[nashorn.jar:?]
at javax.script.AbstractScriptEngine.eval(Unknown Source) ~[?:1.8.0_221]
at org.apache.jmeter.util.JSR223TestElement.processFileOrScript(JSR223TestElement.java:225) ~[ApacheJMeter_core.jar:5.2.1]
at org.apache.jmeter.protocol.java.sampler.JSR223Sampler.sample(JSR223Sampler.java:71) [ApacheJMeter_java.jar:5.2.1]
at org.apache.jmeter.threads.JMeterThread.doSampling(JMeterThread.java:627) [ApacheJMeter_core.jar:5.2.1]
at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:551) [ApacheJMeter_core.jar:5.2.1]
at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:490) [ApacheJMeter_core.jar:5.2.1]
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:257) [ApacheJMeter_core.jar:5.2.1]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_221]
Caused by: jdk.nashorn.internal.runtime.ECMAException: ReferenceError: "AWSCognito" is not defined
at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57) ~[nashorn.jar:?]
at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319) ~[nashorn.jar:?]
at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291) ~[nashorn.jar:?]
at jdk.nashorn.internal.objects.Global.__noSuchProperty__(Global.java:1442) ~[nashorn.jar:?]
at jdk.nashorn.internal.scripts.Script$1312$\^eval\_.:program(<eval>:15) ~[?:?]
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637) ~[nashorn.jar:?]
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494) ~[nashorn.jar:?]
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393) ~[nashorn.jar:?]
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:449) ~[nashorn.jar:?]
... 11 more
Please help me in resolving this issue
There should be no problem to load multiple JavaScript files using load() function, for example:
Given I have foo.js file in "bin" folder of my JMeter installation with the following code:
function foo() {
log.info('foo')
}
And bar.js file with the following code:
function bar() {
log.info('bar')
}
I can call both functions from the JSR223 Sampler like:
load('foo.js')
load('bar.js')
foo()
bar()
So I would recommend checking integrity of your aws-cognito-sdk.min.js file and maybe even take it from the Github instead of relying on the local copy like:
load("https://raw.githubusercontent.com/amazon-archives/amazon-cognito-identity-js/master/dist/aws-cognito-sdk.min.js")
Also be aware that starting from JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting so consider migrating to aws-java-sdk and use groovy language for getting the token, you can use aws-cognito-java-desktop-app as a reference.
It seems your library is causing a script error at
"AWSCognito" is not defined in <eval> at line number 15
Resolving this issue will fix your functionality.

Node.js - process.exit AND append the entire console.log messages in a text file

I'm a noob to Puppeteer.
I'm using a script that login to a site. If username or password is wrong, I want to log the console message in a file AND exit with an error number. This number is important because it will be used in Excel VBA.
I use a file batch (Windows) to run the node.js script, and I use a function at the beginning the script to append the console message.
I run a batch file to run the script:
node C:\*my-path*\node-script.js
exit /b %errorlevel%
I can see the message in the console, but in the log file there isn't the entire error message because process.exit(1) close the procedure before it.
This is the function to append the console.log messages:
fs.unlinkSync("./tmp/node-js.log");
console.log = function(msg) {
fs.appendFile("./tmp/node-js.log", msg+'\r\n', 'ascii', function(err) {
if(err) {
return trueLog(err);
}
});
trueLog(msg);
And then, this is the code to login:
await page.goto('https://google-wrong.com/', { //a wrong url to test
waitUntil: 'networkidle2',
timeout: 10000
}).catch(error => {
throw (console.log('\r\n'+ 'JAVASCRIPT * Wrong Url ! * ' + error)), process.exit(1) });
So, if I use browser.close() instead of process.exit(1) I can append the entire message but can't exit with an error code; this is my console.log:
> Open browser in memory... Done!
> Connect to google-wrong.com... Error!
> JAVASCRIPT * Wrong Url ! * Error: net::ERR_NAME_NOT_RESOLVED at https://google-wrong.com/
And at the Dos prompt I see:
> exit /b 0
If I use process.exit(1), I can see the "exit with error" number:
exit /b 1
...but I can't log the entire message:
> Open browser in memory... Done!
> Connect to google-wrong.com... Error
Any ideas?
Thanks in advance, and sorry for my bad english, I hope I made myself clear.
I think you should use fs.appendFileSync in your console.log function, and no need for the throw keyword in the catch handler

How to make nodejs to talk with golang

I am creating a web app in node.js and golang. I need to connect nodejs with golang code which talks to mongodb and returns data to node program. is there any way to connect so? I tried to use gonode API.This is my code using gonode API.
my node.js file contains below code:
var Go = require('gonode').Go;
var options = {
path : 'gofile.go',
initAtOnce : true,
}
var go = new Go(options,function(err){
if(err) throw err;
go.execute({commandText: 'Hello world from gonode!'}, function(result, response) {
if(result.ok) {
console.log('Go responded: ' + response.responseText);
}
});
go.close();
}); `
And this is the code in my gofile.go file:
package main
import(
gonode "github.com/jgranstrom/gonodepkg"
json "github.com/jgranstrom/go-simplejson"
)
func main(){
gonode.Start(process)
}
func process(cmd *json.Json) (response *json.Json) {
response, m := json.MakeMap()
if(cmd.Get("commandText").MustString() == "Hello") {
m["responseText"] = "Well hello there!"
} else {
m["responseText"] = "What?"
}
return
}
This is the error am getting while running as node node.js in terminal
events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:905:11)
at Object.afterWrite (net.js:721:19)
Golang from 1.5, you can build go to shared object binary file (*.so). This allows you to connect your go compiled library to be called by nodejs, python, ruby, java etc.
Here is a guide you could refer to: https://medium.com/learning-the-go-programming-language/calling-go-functions-from-other-languages-4c7d8bcc69bf
thanks for the response. I got a solution for this. I made 2 different servers. One for NodeJS and another for Golang. I am calling golang uri in Node server and getting data from golang server.
Based on a very cursive check of the gonode source code, the module seems to spawn go code as a child process and communicate through stdin/-out. EPIPE error means that the other end closed the stream. Based on this it might be that your go process exits prematurely.
You could try to debug the problem by modifying Command.prototype.execute in gonode/lib/command.js to print out the JSON that's sent to the go process. Then you can debug the go program by running it directly and giving it the same input via stdin.

Categories