Node js app running inside container opens user's web browser - node.js

I need an option to open user's default web browser from node js app which is running inside docker container. I need to know that to implement OAuth flow.
I know that I can do it by opening new tab on the client side, but I don't have this option for other reasons.

I'm not familiar with docker container, but for just straight nodejs, this works for me:
// start browser
if (opSys == "Win64")
command = ("start http://localhost:8000/init"); // Win64
else if (opSys == "MacOS")
command = ("open http://localhost:8000/init"); // MacOS
else
command = ("xdg-open http://localhost:8000/init"); // Linux
exec (command, function (error, stdout, stderr)
{
if (error)
{
console.log ("command: ", command);
console.log ("error: ", stderr);
}
});

Related

Is there any way to get a hook or event in Electron JS when a new application is launched

I'm new to Electron JS. Trying to build a cross-platform desktop application to watch user activities.
My requirement is when a user moves out of my application and opens some other application like a browser/ calculator, is there any way that can be monitored from my application?
Please advice. Thanks
You can use this electron api:
let spawn = require("child_process").spawn;
let bat = spawn("cmd.exe", [
"/c", // Argument for cmd.exe to carry out the specified script
"D:\test.bat", // Path to your file
"argument1" // Optional first argument
]);
bat.stdout.on("data", (data) => {
// Handle data...
});
bat.stderr.on("data", (err) => {
// Handle error...
});
bat.on("exit", (code) => {
// Handle exit
});
Make sure to put the correct path to your batch file (here is an example to find notepad):
tasklist | find /i "notepad.exe" && echo true || echo false
Make sure to handle only false, because true will log notepad.exe info, too.
P.S.: The batch script works only for Windows, I don't know how to create the bash version.

Node PhantomJS script onResourceError path issue

Having some trouble using the webpage API in a phantomJS script I'm using for load testing.
I'm running the script in a child process, like so:
var path = require('path');
var childProcess = require('child_process');
var binPath = require('phantomjs').path;
var childArgs = [
path.join(__dirname, 'phantom-script.js')
];
var spawn = childProcess.spawn;
var child = spawn(binPath, childArgs);
child.stdout.on('data', function(data) {
const buf = Buffer.from(data);
console.log('stdout:', buf.toString());
});
child.stderr.on('data', function(data) {
const buf = Buffer.from(data);
console.log('stderr:', buf.toString());
});
And my simple phantomJS script:
var webPage = require('webpage');
var page = webPage.create();
page.onConsoleMessage = function (msg) {
console.log(msg);
};
page.onResourceError = function(resourceError) {
console.log(resourceError.errorCode + ':', resourceError.errorString);
};
function runScript() {
page.open('<webpage-url>', function(status) {
console.log('Status:', status);
if (status === 'success') {
page.evaluate(function() {
console.log('Title:', document.title);
});
}
});
}
runScript();
So to start the phantomJS script, if both of these files are in the test/ directory, and my current directory is up one from that: node test/child-process.js, which then spawns the child process and runs my phantomJS script.
So, this gets the script to run, but it always fails in page.open because of a resource error. Replacing my url with Google's, or really any website, works fine.
The error logged in onResourceError is stdout: 202: Cannot open file:///Users/<user>/path/to/local/current/directory: Path is a directory.
This is always the path from which I'm running this script. If I move down a directory into test/ and run it with node child-process.js, the error instead logs that directory.
As a headless browser, I assumed phantomJS would interface with a webpage like any client would, just without rendering the template--what does the current directory from which the script was run have anything to do with opening the webpage? Why would it be trying to load resources from my local directory when the webpage URL points to a public website, hosted at the IP and PORT specified in the first argument of page.open (e.g. xx.xxx.xx.xx:PORT)?
I'm at a bit of a loss here. The phantomJS path and all that is correct, since it runs the script fine. I just don't understand why page.open would attempt to open the directory from which the script was called--what does that have to do with its function, which is to open the URL and load it to the page?
Not sure if this is even worthy of answering--as opposed to just deleting.
I figured it out when I manually typed in the argument www.google.com, instead of copy/pasting from the browser, and and I got this as the path in the error: file:///Users/<user>/path/to/local/current/directory/www.google.com.
Now I know why I couldn't find a SO question for it. A stupid error on my part at any rate, it would've been a quick debug if the error had appended the IP address and PORT (my "url") to the end of the file path like it did for www.google.com, a clear indicator that it's not pinging a URL.
TL;DR: It's a URL, you need http(s)://...

Node.js open Chrome Ubuntu 16.04 LTS

This is a similar question to here. However I am using Ubuntu and the previous question's accepted answer does not seem relevant.
I am using node to call a shell script that in turn calls chrome. A terminal opens and echo's the url but chrome browser does not open. I have also tried /usr/bin/google-chrome after discovering it from which command as well as google-chrome-stable to no avail. Why doesn't chrome launch on Ubuntu with node.js child process? Im running desktop version 16.04 LTS. If I run this shell script on the terminal without node it runs great.
JS:
var exec = require('child_process').exec,
child;
child = exec('gnome-terminal -x '+__dirname+'/ss.sh http://www.google.com',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
SHELL (ss.sh)
#!/bin/bash
echo $1
google-chrome $1 --start-maximized
OUTPUT:
Edit: I just tried running this on another box running Ubuntu 14.04 and receive the error: failed to create /home/user/.pki/nssdb directory. The plot thickens.
JAVA: If I run this with almost the same code in Java it works perfectly:
public static void main(String[] args) {
try {
String url = args[0];
ProcessBuilder pb = new ProcessBuilder("/home/user/ss.sh", url);
pb.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The answer to this was file permission and it came from #paulsm4 comment. He references #A.B. answer from here.
As soon as he posts his comment as an answer I will accept and delete this.

How to Know if an specific windows service is installed with Node js?

I'm new in Node JS.
I'm building an new desktop app with web-kit.
One of my requirements is verify if an determinate service is installed on Windows. How can I do that on Node js?
I know how to find the application at the process list with Node Js. But what I really need is whether it is installed, because it can be stopped, but installed.
This will get you an array of all installed services:
var exec = require("child_process").exec;
exec("sc query state= all", function(err, stdout) {
var lines = stdout.toString().split("\r\n").filter(function (line) {
return line.indexOf("SERVICE_NAME") !== -1;
}).map(function (line) {
return line.replace("SERVICE_NAME: ", "");
});
console.log(lines);
});

Node.JS windows service cannot start

I'm using windows-service package to run my script as a windows service.
if (process.argv[2] == "--add") {
logger.info('Starting to add service', global.appRoot + "\\app.js")
ws.add (config.service_name, {programPath: global.appRoot + "\\app.js"});
logger.info('Service added', config.service_name, global.appRoot + "\\app.js")
} else if (process.argv[2] == "--remove") {
logger.info('Removing service', config.service_name)
ws.remove (config.service_name);
logger.info('Service removed', config.service_name)
} else if (process.argv[2] == "--run") {
logger.info('Starting service', config.service_name);
ws.run (logger, function() {
logger.info('Stopping service', config.service_name);
ws.stop()
logger.info('Service stopped')
});
} else if (process.argv[2] == "--stop") {
logger.info('Stopping service', config.service_name);
ws.stop()
logger.info('Service stopped')
}
After running "node service.js --add", I have verified that my windows service is installed correctly with command like below
"C:\Program Files\nodejs\node.exe" "E:\Utils\app.js"
I pasted the command into node.js command prompt and it launched the script correctly.
However, when I tried to start the windows service from the service console, it always complains
Error 1053: The service did not respond to the start or control request in a timely fashiion.
I tried "node service.js --run", it simply prints out the "Starting service" message and hangs there. The underlying script isn't kicked off either.
Verified service log, no error. No script-specific log is generated.
All my script objects are using global.appPath for absolute path reference.
I run out of ideas. Any advice on this matter?

Resources