How to pass command line argument in electron - node.js

I just started using electron. I have a doubt about how to pass command line arguments in electron when I'm using npm start to run electron.
In Node.js I am using: node server.js one two=three four
command prompt for :
var arguments = process.argv.slice(2);
arguments.forEach(function(val,index, array) {
console.log(index + ': ' + val);
});
In Node.js is working. I need to know how can I make this work in electron.
Can someone please give a solution for this?

The way of passing arguments will be same, the only thing you have to take care is path of electron. In package.json its written npm start will perform electron main.js. So you will have to execute this command explicitly and pass arguments with "proper path of electron" i.e ./node_modules/.bin/electron. Then the command will be
./node_modules/.bin/electron main.js argv1 argv2
and these arguments you can access by process.argv in main.js
and If wish you to access these parameters in your app then there are following things to do :
1.In your main.js define a variable like
global.sharedObject = {prop1: process.argv};
2.In your app just include remote and use this sharedObject
const remote = require('electron').remote;
const arguments = remote.getGlobal('sharedObject').prop1;
console.log(arguments);
3.Output will be ["argv1", "argv2"]

Related

Error: Environment Vairable name is not recognized as an internal or external command in NodeJS

I am not very experienced in Nodejs but I am trying to fetch some some information in my node app that I will pass from CMD/terminal that I will access through process.env in my app.
For example, I want to pass PORT NUMBER through env in my node and fetching the same using below line:
const PORT = process.env.PORT || 3001
and I am passing port number at the time of running node app using below command line:
node server.js PORT=4200
The above one is not working. After searching on google, many people giving solution to achieve the same by running below command line:
PORT=4200 node server.js
By running above command, I am getting error in command line as given below:
'PORT' is not recognized as an internal or external command, operable program or batch file.
Can someone please let me know, how can I pass variable at the time of running node app and access the same in node app. I don't want to use any env file. I just only want to pass info from command line.
Thanks in advance
Command-line arguments are traditionally passed in via the process.argv array. argv[0] contains the process name node, argv[1] contains the first command line argument, etc... So, you can run:
node server.js 4200
and from node, do:
const port = parseInt(process.argv[1], 10);
See How do I pass command line arguments to a Node.js program?
If you must use environment variables, Node's process.env contains the environment variables of the node process.
The set command is used to store a value in an environment var on Windows. Then run node:
set PORT=4200
node server.js
More examples of the set command can be found here: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/set_1#examples .

How to find an .exe file path using node js

I'm running electron and nodejs on Windows 10
How can I find a path to an executable?
one way would be to run a cli command that will use something like
where myfile.exe
is there a node-ish way?
Use which module:
var which = require('which')
// async usage
which('node', function (er, resolvedPath) {
// er is returned if no "node" is found on the PATH
// if it is found, then the absolute path to the exec is returned
}).

How to disable warnings when node is launched via a (global) shell script

I am building a CLI tool with node, and want to use the fs.promise API. However, when the app is launched, there's always an ExperimentalWarning, which is super annoying and messes up with the interaction prompts. How can I disable this warning/all warnings?
I'm testing this with the latest node v10 lts release on Windows 10.
To use the CLI tool globally, I have added this to my package.json file:
{
//...
"preferGlobal": true,
"bin": { "myapp" : "./index.js" }
//...
}
And have run npm link to link the ./index.js script. Then I am able to run the app globally simply with myapp.
After some research I noticed that there are generally 2 ways to disable the warnings:
set environmental variable NODE_NO_WARNINGS=1
call the script with node --no-warnings ./index.js
Although I was able to disable the warnings with the 2 methods above, there seems to be no way to do that while directly running myapp command.
The shebang I placed in the entrance script ./index.js is:
#!/usr/bin/env node
// my code...
I have also read other discussions on modifying the shebang, but haven't found a universal/cross-platform way to do this - to either pass argument to node itself, or set the env variable.
If I publish this npm package, it would be great if there's a way to make sure the warnings of this single package are disabled in advance, instead of having each individual user tweak their environment themselves. Is there any hidden npm package.json configs that allow this?
Any help would be greatly appreciated!
I am now using a launcher script to spawn a child_process to work around this limitation. Ugly, but it works with npm link, global installs and whatnot.
#!/usr/bin/env node
const { spawnSync } = require("child_process");
const { resolve } = require("path");
// Say our original entrance script is `app.js`
const cmd = "node --no-warnings " + resolve(__dirname, "app.js");
spawnSync(cmd, { stdio: "inherit", shell: true });
As it's kind of like a hack, I won't be using this method next time, and will instead be wrapping the original APIs in a promise manually, sticking to util.promisify, or using the blocking/sync version of the APIs.
I configured my test script like this:
"scripts": {
"test": "tsc && cross-env NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 jest"
},
Notice the NODE_NO_WARNINGS=1 part. It disables the warnings I was getting from setting NODE_OPTIONS=--experimental-vm-modules
Here's what I'm using to run node with a command line flag:
#!/bin/sh
_=0// "exec" "/usr/bin/env" "node" "--experimental-repl-await" "$0" "$#"
// Your normal Javascript here
The first line tells the shell to use /bin/sh to run the script. The second line is a bit magical. To the shell it's a variable assignment _=0// followed by "exec" ....
Node sees it as a variable assignment followed by a comment - so it's almost a nop apart from the side effect of assigning 0 to _.
The result is that when the shell reaches line 2 it will exec node (via env) with any command line options you need.
New answer: You can also catch emitted warnings in your script and choose which ones to prevent from being logged
const originalEmit = process.emit;
process.emit = function (name, data, ...args) {
if (
name === `warning` &&
typeof data === `object` &&
data.name === `ExperimentalWarning`
//if you want to only stop certain messages, test for the message here:
//&& data.message.includes(`Fetch API`)
) {
return false;
}
return originalEmit.apply(process, arguments);
};
Inspired by this patch to yarn

Run Node Package + Arguments from another script

I've found myself in a situation where I'm having to run a single command e.g. node compile.js
that .js file needs to run the following
browserify -t jadeify client/app.js -o bundle.js
All the dependencies are installed, and by running this command in the CLI works fine, just need to figure out how to execute it from within a node script.
We've also got inside our package.json the following which contains something similar to
"script" : [ "compile": "browserify -t jadeify client/app.js -o bundle.js" ]
this works perfectly when you execute cd /project && npm run compile via ssh however not via exec
Thanks
You should be able use the api-example and extend it with the transform as suggested by the jadeify setup paragraph.
var browserify = require('browserify');
var fs = require('fs');
var b = browserify();
b.add('./client/app.js');
// from jadeify docs
b.transform(require("jadeify"));
// simple demo outputs to stdout, this writes to a file just like your command line example.
b.bundle().pipe(fs.createWriteStream(__dirname + '/bundle.js'));
You can access script arguments via process.argv.
An array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.
You can then use the browserify api together with jadeify to get what you need.
var browserify = require('browserify')();
var fs = require('fs');
var lang = process.argv[2];
console.log('Doing something with the lang value: ', lang);
browserify.add('./client/app.js');
browserify.transform(require("jadeify"));
browserify.bundle().pipe(fs.createWriteStream(__dirname + '/bundle.js'));
Run it with $ node compile.js enGB

Running console commands through node inspector?

I have connected node inspector to my running node.js program. But I'd like to issue commands through the console - not necessarily on a breakpoint. For example, I have global variables and functions in my server.js program. For example:
var express = require('express');
var app = express();
function test() {
console.log('yo');
}
app.listen(3000);
Now in node-inspector I go into the console and I type 'test()' and it returns "ReferenceError: test is not defined", same things with global variables I type 'app' and it tells me it's not defined. Any idea how to make this thing work? I just want to run my node program and then issue commands to it via a command line interface.
#foreyez,
Your question inspired me to make an npm module that lets you debug (via command line) a running node.js application without setting breakpoints or needing to make variables global:
https://github.com/go-oleg/debug-live
Hope that helps!
The reason why it doesn't work as you expected is that all your variables and functions are local to your module (application) and you can't access them from a global context.
You can save them in the global scope if you want to access them from anywhere (including from the console when not stopped on a breakpoint):
var express = require('express');
var app = express();
function test() {
console.log('yo');
}
app.listen(3000);
global.test = test;

Resources