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

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.

Related

RethinkDB: Loading A NodeJS package inside r.js method

I am not sure is it possible or not.
I need to use a t-distribution in my ReQL from a nodeJS Package. The code is something like this:
Query.map(function(doc){
return {
'DesScore': r.do(doc('MXt'),
doc('MXdf'),
r.js('(function(v,df){
var distributions = require("distributions.js");
var studentt = distributions.Studentt(df);
return studentt.inv(-1.*Math.abs(v))*2.*100.;}) '))
};
})
But I get
Unhandled rejection ReqlQueryLogicError: ReferenceError: require is not defined in:
How can I load a package in ReQL js interpreter?
Thanks in advance for any help.
You cannot use require in r.js because it's JavaScript v8, not NodeJS. require is come from NodeJS API, it isn't in standard JavaScript. On JavaScript client side, people use browserify (or friend) for that purpose. So to use require, you have to implement a shim for require inside r.js, which may also pull it other dependencies...
More than that, you also have to somehow distribute your dependencies to RethinkDB server itself for require to work.
All of those are a mess. So probably try to find another solution.
Think of r.js as the last way to do something, and try to use native ReQL whenever possible, as the document say:
https://www.rethinkdb.com/api/javascript/js/
With control structure like forEeach, do, branch I think you can do pretty much stuff with it.

Maintaining Certain Variables when using UglifyJS

I have a custom script that uses jQuery with the shorthand $("selector")notation. When I run my script through Uglify, the $ gets changed to a random letter, like a "e" or something, causing my jQuery functions in my script to break. How can I ensure that the $ doesn't get changed? I'm using Gulp for build, so is this something I need to set in my gulpfile?
Just for anyone that may see this in the future, I passed mangled: false as an option when using the uglify task in my gulpfile to solve this.

How can I use an emscripted .js library in a Web Worker

I've compiled my program into a single program.js file, and within the worker, I call:
importScripts('program.js');
Module.callMain();
However, although callMain is executing, within that function invocation's stack I am getting the Undefined is not a function error.
My hunch is that I haven't read some essential emscripten documentation, wiki, or sourcecode.
What I know:
emscripten has bindings to work with workers, but only when there is an emscripted process on the main thread to use these bindings (see emscripten.h)
In order to compile a task (within a library that runs on the main thread) to a worker, emcc needs special options passed at compile time for that task (see settings.js)
What I surmise:
There may be flags that I need to pass to let emcc know not to call functions on nonexistent objects, like window
Having looked through the implementation of /dev/tty, which is linked to by /dev/stdin, and the implementation of /dev/stdout, I believe there may be output to the console, which I don't believe is supported in a worker
What I am asking:
How can I use my library, a single js file, in a worker?
My library loads other files from a program.data file, if that makes a difference
Thanks in advance. Please let me know if I can add any details.
Note: the code at top is simplified - it doesn't seem to be an error in syntax.
Update:
The stacktrace (Error.stack) only tells me that the error occured in Module.callMain. It does not tell me anything about the imported script that might be causing it. :(
Emscripten output should run on a website, on a web worker, or in node, all without modifications. There might be some limitations (e.g. no canvas to render to in a worker), but otherwise it is just pure JS that can run in those three environments.
Does the exact same JS file that emscripten generated work outside of a worker?
If callMain() fails, check that your project has a main() function.
Immediately after loading the js (by importScripts()) it may not be executed yet, hence you are not ready. You can ask Emscripten to call a callback for you when things are ready. You will have functions accessible via the variable Module.
var Module = {
preRun:[],
onRuntimeInitialized: function load_done_callback() {
console.info("The Module is loaded and is accessible here", Module);
console.inf("no need to call main() though", Module._main); // add "_" before your function names
},
};
importScripts('program.js');
No need to call callMain() or Module._main(), it will be called for you. You may need to set NO_EXIT_RUNTIME=1 in compiler command line:
em++ \
-s EXPORTED_FUNCTIONS="['_main', '_myfunction1' , '_my_function2' ]" \
-s NO_EXIT_RUNTIME=1 \
-s DEMANGLE_SUPPORT=1 \
program.cpp \
-o ./program.js
Note that you don't need to compile as worker in this case where you use importScripts().

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

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 });

How to make the coffeescript compiler ignore part of a source file?

My use case is the following:
I decided to try coffeescript for some nodejs project and i want some of my source files to begin with #!/usr/bin/env node
Coffeescript treats lines that begin with # as comments.
I know that you can embed js code in .coffee but that is not the case because
file.coffee
`#!/usr/bin/env node`
foo = 'bar'
Compiles to:
file.js
(function() {
#!/usr/bin/env node;
var foo;
foo = 'bar';
}).call(this);
The compiler doesn't support this. See: https://github.com/jashkenas/coffee-script/issues/2215
But why not run it with coffee instead?
#!/usr/bin/env coffee
console.log 'Hello World'
Then just run ./my_code.coffee. The coffee executable is simply a wrapper around node, and can be used instead in nearly all circumstances.
Or create some sort of build system that tacks it on after the compile step. But you shouldn't really need to.
What you want is not possible with CoffeeScript, though you could - as Alex Wayne suggested - prepend the shebang manually to the file if you want to.
What I did for a project of mine, is making a very small JS script with a she-bang, that loads the JS code compiled from CoffeeScript. See this file https://github.com/meryn/jumpstart/blob/master/bin/jumpstart . This works well.
Another advantage of doing this is easier testing. You don't have to start a new child process to run the code. Instead, you can use call the run function, or however you have called it. This of course leaves the problem of passing proper parameters. I did this by making the run function (see https://github.com/meryn/jumpstart/blob/master/src/run.coffee for source) delegate practically everything to runWith function which can be passed all the input variables (environment, cli args, etc) the script needs.

Categories

Resources