Load a javascript object from file in nodejs, parse error - javascript

I'm having trouble while trying to load the following javascript object from a file with NodeJS:
{
queries:{
user:"SELECT * FROM users WHERE $1 = ?"
},
user:function(identifier){
return this.queries.user.replace('$1', "user_"+identifier);
}
}
With the require function:
var queries = require('./components/queries');
I get a parsing error on line 4, unexpected ',' right after the queries ending curly bracket.
I'm not sure what is wrong with this object since I can declare it in chrome console without any trouble, so I bet the issue is related with the way I include this piece of code in my main script. But I don't know how to include it properly.
Thanks for your help !

In commonJS you should use the exports object to set access to module variables.
exports.queries = {
queries:{
user:"SELECT * FROM users WHERE $1 = ?"
},
user:function(identifier){
return this.queries.user.replace('$1', "user_"+identifier);
}
}
And then add it like this:
var q_mod = require('./components/queries');
var queries = q_mod.queries;
//logs "SELECT * FROM users WHERE $1 = ?"
console.log(queries.queries.user);

You have 3 ways to do what you want:
Change the extension of the file to .json
Export the content as a node.js module:
module.exports = /* the object */
Read and parse it as a json file:
fs.readFile('path/to/file', function (content) {
var queries = JSON.parse(content.toString());
});

Related

Electron - How to pass JSON from main window to remote window?

I'm working with a total of 3 files.
index.html:
...
subWindow
...
The fetch() function returns a callback in JSON format.
subWindows.js:
let micWindow
function subWindow(data) {
micWindow = new BrowserWindow({
width: 1280,
height: 800
})
console.log(data)
micWindow.show()
micWindow.loadFile('src/subWindow.html')
micWindow.webContents.on('did-finish-load', function() {
let javascript = `document.querySelector('body').innerHTML = '` + data + `'`
micWindow.webContents.executeJavaScript(javascript)
})
}
And finally subWindow.html which contains pure html. It also imports subWindows.js:
...
<!-- JS Imports -->
<script src="js/subWindows.js"></script>
...
Firstly, index.html console log prints JSON data for both onclick and subWindow() at MIC.js?[sm]:10. The subWindow.html shows [object Object] from executeJavascript, but the console is empty.
Secondly, doing the following doesn't work:
let javascript = `document.querySelector('body').innerHTML = '` + JSON.stringify(data) + `'`
or
let javascript = 'console.log(' + data + ')'
Both throw an exception Uncaught SyntaxError: Unexpected identifier in subWindow.html
JSON data isn't rendered by subWindows.js in subWindow.html but rather in index.html:
index.html imports <script src="js/subWindows.js"></script>
Why is it throwing an error?
How to pass JSON data from main to remote window as function parameter?
Preferably pass JSON to executeJavascript and inject it back into remote window's html.
Thanks for any feedback!
I'm not sure about the errors, but my solution is to put the data into the window by editing the HTML. Here is one way to do this:
// win is the window you are passing info to
var data = win.document.createElement('span');
data.innerHTML = json;
win.document.body.appendChild(data);
The program in the window would wait for the element to appear, and then use the value for the function.
Note:
I just noticed that your JavaScript doesn't have any semicolons at the end of the lines. You need to have one after every statement. :)

replace entire variable line using partially matched regex in javascript from an external file

I've two files. Lets call them first.js and second.js.
Since second.js is called by html, I cant use require. So I am trying to modify a parameter in second.js from first.js.
First is running on a node.js server. I need to replace/update ipAddress variable value from second.js every-time I run first.js
So in first.js , I am trying to use external replacemodule (any other way is ok as well).
First I open external file (second.js) from first.js, then search for
var ipaddress = "192.168.0.10"
This ip address changes everytime. So I am trying to search on var ipaddress and need to to replace it with variable ipaddr.
Here is what I have so far.
Partial contents of first.js.
function replaceIP(ipaddress){
var replace = require("replace");
replace({
regex: "^var ipAddress.*$",
replacement: "var ipAddress = " + ipaddr,
paths: ['./second.js'],
recursive: false,
silent: false,
});
}
This is not working.
If I just use hardcoded value for iPAddress , like
var ipAddress = 'XXXX';
And the replace 'XXXX'. Its working fine.
So I know it has to be with RegEx and not 'Replace' Module.
EDIT:
Also problem is second.js ipAddress variable will store different value for every login session , Hence I cant grab onto entire string since I dont know what it will be, Hence I am grabbing onto starting portion (^var ipAddress) of declaration statement.
e.g first login : var ipAddress = '192.168.0.10';
second login session: var ipAddress = '192.168.0.12';
third login session: var ipAddress = '192.168.0.18';
and so on.
Here is an example that replaces entire line in python based on partial match of string.
Can I do something like this in javascript?
Any ideas?
PS: I looked at few other Q & A on SO, and it does not seem to address the issue.
Thanks.
I was able to solve above using shell.js which offers straigt-forward unix like shell commands across platform. Really impressed with its ease of use.
I guess the key was searchPattern = /^.*var ipAddr =.*$/;
function replaceIP(ipAddr) {
var shell = require("shelljs");
var searchPattern = /^.*var ipAddr =.*$/;
var replacePattern = "var ipAddr = '" + ipAddr + "';";
var cwd = shell.pwd().stdout;
var file = cwd + '/second.js';
shell.sed('-i', searchPattern, replacePattern, file);
console.log("replacing " + ipAddr + " in file " + file);
}
Then call using,
replaceIP(ipAddr)

Execute a node script with from inside a file

Strange question, but currently I have a script that I run from the terminal which requires a parameter. Normally I will run this by doing node script.js param, but now I want to run this script with the parameter from inside a JS file when the Express server loads.
The parameter is taken in and defined in the file like this:
var param = process.argv[process.argv.length - 1];
What is the best practice for making this file accessible elsewhere in my Node app and running it?
If I understand you correctly following should work.
script.js
module.exports = function (params) {
console.log(params);
}
main.js
var param = process.argv[process.argv.length - 1];
require('./script')(param);
If you need to get param from another source when the script is required you can make a verification if the script is running directly from command line or it was required:
if (require.main === module) {
var param = process.argv[process.argv.length - 1];
} else {
var param = // get from other source.
}

How to load external js library in Jmeter?

I have the following code in a jsr223 sampler:
var key = "key";
var dateStamp = "20160329T134359Z";
var regionName = "us-east-1";
var serviceName = "execute-api";
var kDate= Crypto.HMAC(Crypto.SHA256, dateStamp, "AWS4" + key, { asBytes: true})
var kRegion= Crypto.HMAC(Crypto.SHA256, regionName, kDate, { asBytes: true });
var kService=Crypto.HMAC(Crypto.SHA256, serviceName, kRegion, { asBytes: true });
var kSigning= Crypto.HMAC(Crypto.SHA256, "aws4_request", kService, { asBytes: true });
vars.put("AWSKey", kSigning);
Now when I run it i get this error:
Response code: 500
Response message: javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "Crypto" is not defined. (#6) in at line number 6
Obviously I dont have the crypto libs. However I am at loss on how to load them. I downloaded all the relavant js and put them in the /lib folder and still nothing.
I downloaded this file: https://github.com/Boussetta/CryptoJS-v3.1.2
Which handles the functions in the code above but for the life of me I have not idea how to import it.
TIA
If you want to go for JavaScript - there are 2 options:
Use Rhino load() method like:
load("crypto.js")
Use HmacUtils class from Apache Commons Codec from JavaScript
var rawhmac = org.apache.commons.codec.digest.HmacUtils.hmacSha1(key,data)
var encoded = org.apache.commons.codec.binary.Base64.encodeBase64String(rawhmac)
However I would recommend going for option 3 - switch to "groovy" language instead of JavaScript, that way you will be able to:
Re-use Amazon authentication samples in your test
Get maximum performance and confidence as groovy scripts can be compiled while other languages are interpreted so groovy implementation will take less resources and will work faster. See Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You've Been Waiting For! article for more details.

Change query argument of jQuery suggest plugin

This question is kind-of crappy because I try to get around some limitations:
Current JS sends an ajax query with the following code
jQuery('#searchbox').suggest('/?live=1');
What the server get is the following query string:
?live=1&q=searchstring
Problem:
The server expects the query string to be preceded with 's=' not 'q='
I have to use the existing scripts so what I'm trying to so is find a way to change 'q=' to 's=' in javascript, without altering the exisiting suggest plugin or the php search script.
Thanks.
The only way you will do that is by modifying the plugin, if you want to avoid changing the script forever and need this only for one page, override the function temporarily.
$.suggest.suggest = function() {
var q = $.trim($input.val());
if (q.length >= options.minchars) {
cached = checkCache(q);
if (cached) {
displayItems(cached['items']);
} else {
//This is the line we r changing
$.get(options.source, {s: q}, function(txt) {
$results.hide();
var items = parseTxt(txt, q);
displayItems(items);
addToCache(q, items, txt.length);
});
}
} else {
$results.hide();
}
}

Categories