How do I handle command-line arguments in a mongo script? - javascript

I've been working on some simple scripts to run on mongo from the bash command-line. Originally, I ran them as follows:
$ mongo dbname script.js
but I recently came across mikemaccana's answer, https://stackoverflow.com/a/23909051/2846766, indicating the use of mongo as an interpreter so I can just execute script.js (or any name I choose, with or without the .js) from the command line.
$ script.js
I think it's brilliant and clean, but now I'd like to pass in a database name as a command line argument.
$ script.js dbname
Here I use the bash-style "$1" to demonstrate what I'm doing in script.js.
#!/usr/bin/env mongo
var db = new Mongo().getDB($1);
// Do other things with db, once I resolve the name from the command line.
This results in a "ReferenceError: $1 is not defined ...", which is not surprising. But how would I reference command line arguments? Is this going to be a mongo convention? a javascript convention? Is it possible? It would make my command-line experience with mongo much better aesthetically.

Currently there is no way to do this using the mongo shell...
https://groups.google.com/forum/#!topic/mongodb-user/-pO7Cec6Sjc
... try using a bash script (or other scripting language you are comfortable with) if you want to get a similar command line experience.

Duplicate of How to pass argument to Mongo Script
In a nutshell, this is not possible but several workarounds are given in the answers (not repeated here).

You can pass args to your script through
mongo --eval 'var databasePassword="password"' script.js
and you can access databasePassword value inside script.js
db.auth({ user: 'testUser, pwd: databasePassword });

Related

The term “URL=Test.com” is not recognized

I have the following in my test file. I’m trying to use env variables on my scripts then send the value thru commandline.
const MYURL = process.env.URL;
console.log(MYURL)
In the commandline when I run the following:
URL=Test.com npx playwright test
I get an error message:
The term ‘URL=Test.com’ is not recognized as the name of the cmdlet..etc.
Because you use bash syntax in Powershell. Powershell does not set env variables like var=value, so this syntax won't work.
You probably need to read something like this to figure out the right syntax for Powershell.

Call a java script file in mongodb shell

I tried to run a JS file directly from the Mongo shell by using the query
mongo localhost:27017/west createSumCollection.js
However I keep getting the error
"uncaught exception: SyntaxError: unexpected token: identifier :
#(shell):1:6"
The contents of CreateSumCollection.js are a simple use database and db.createCollection with a simple object id and another field.
Any idea what I am missing here? If I run the same script in the mongoshell directly it works perfectly.
I tried load("C:/mongodb/data/db/createSumCollection.js") and it failed because of the use west statement inside the .js file. So after removing that, the load worked. My question is what is the difference between load and mongo localhost:27017/west createSumCollection.js and how do i get the js to be run directly.
use is a helper that is only available in the interactive shell.
In the interactive shell (and via load) you might run:
use my_database
db.collection.find()
The equivalent in a javascript file on the command line would be:
db.getSiblingDB("my_database").collection.find()

Nodejs library without nodejs

How can I integrate a nodejs library into my non nodejs project?
I am particularly needing this library:
https://github.com/greenify/biojs-io-blast
BioJS uses Browserify CDN to automatically generate a single JS file for usage. Either include
<script src="http://wzrd.in/bundle/biojs-io-blast#latest"></script>
in your html or download the JS file via this link.
We also have a live JS Bin example here.
Yes, you can do it using a Publisher/Subscribe pattern and a Queue library, such as RabbitMQ.
In the example below, the author is communicating a python script with a NodeJS one, using the RabbitMQ clients for each platform.
https://github.com/osharim/Communicate-Python-with-NodeJS-through-RabbitMQ
The code for sending from NodeJS:
var amqp = require('amqp');
var amqp_hacks = require('./amqp-hacks');
var connection = amqp.createConnection({ host: "localhost", port: 5672 });
connection.on('ready', function(){
connection.publish('task_queue', 'Hello World!');
console.log(" [x] Sent from nodeJS 'Hello World!'");
amqp_hacks.safeEndConnection(connection);
});
Then, receiving in python:
#!/usr/bin/env python
import pika
import time
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
#our callback
def suscriber(ch,method , properties , body):
print "[Y] received %r " % (body,)
time.sleep( body.count('.') )
print " [x] Done"
ch.basic_ack(delivery_tag = method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(suscriber, queue = 'task_queue')
print ' [*] Waiting for messages from Python. To exit press CTRL+C'
channel.start_consuming()
to integrate any node library you use the package manager NPM https://www.npmjs.com/ so to integrate your library do as follow
open terminal
cd path/to/your/project_dir
type this line
npm install biojs-io-blast
This is the more common use case. Some of the node.js libraby, i like them too much i want to use it everywhere. But this library, what i see uses core modules of node.js like fs. I dont think you can use it without node dependency || node binary. But as Code Uniquely or others folks says, if you are using webpack as a build/dev. You can try, browserify or BioJS
The node_module which provided is kind of xml parser. You can't add nodejs library (node_module) to non nodejs programs. You can get xml parser for Blast depending on kind of programming language you are using.
For example :
For PHP phpBlastXmlParser and
For java this might helpfull

Where to place JS files for NodeJS to see them

I've just installed NodeJS on my Mac, and i got it working in the terminal, using inline scripting like "console.log('Hello world'); works fine.
But where do i place JS files for NodeJS to find them? Can i specify the root folder NodeJS to look for file in?
I followed this guide: http://nodeguide.com/beginner.html#learning-javascript
but i cannot get any of the samlpe to work where i reference a script file.
You put them in whatever folder you want. It is common practice to put each application in a different folder.
Then you run node.js like this:
node /path/to/file.js
Or like this:
cd /path/to/
node file.js
Where file.js might look something like this:
console.log('hello world');
You'll have to navigate to the correct folder "manually", in the Node Command Line Interface (CLI).
If you need to change drives, type the drive letter and a colon to switch to that drive, like so;
C:> (<- this is the line prompt, yeah? Just add this after it -> D:
That changes the drive. Now write cd (CD = "Change Directory") and the name of the direcotry you want to go to the directory your stuff is in:
D:> (<- the new prompt. Write something like this after it: ->) cd myprosject\subfoldername
D:\myproject\subfoldername> (<- your new line prompt - if "myproject\subfoldername" exists)
now ask node to execute your script (that is stored in myproject\subfoldername, like so;
D:\myproject\subfoldername> node helloworld.js
Remember to write "node" first - otherwise the command won't go to node, but to the OS, which will probably just open up the js file in a text editior instead of running the goodies inside.
It is very easy.. Go to your command line. navigate to the file location..
then simply run the node helloworld.
I'm not sure I understand. it doesnt 'look' anywhere for your .js files you point at them when you run node. Like so, on the command line:
node mynodeapp.js
If you're meaning where does it look for your .js files as modules, when requirign them, like so:
var mymodule = require("mymodule");
Then it will look inside a folder names node_modules. But I'm sure you're looking for my first example above.

Passing args to a JS command line utility (Node or Narwhal)

I want to use NodeJS or Narwhal to create a JS utility which takes an argument, like so:
$ node myscript.js http://someurl.com/for/somefile.js
or
$ js myscript.js http://someurl.com/for/somefile.js
but I'm wondering how I can get that argument within my script, or if that is even possible atm?
Thanks.
On Node.JS, that information is available in process.argv.
process.arg[2] should be the reference. Check for process.argv.length to see if it's 3.
Docs
You can use optimist, a module for node.js that makes processing args a bit easier.
This things now are very easy to do, using stdio module for NodeJS.

Categories

Resources