Node.js and PowerShell Commands/Scripts - javascript

Here is the folder structure for my node.js project:
MySampleApp\
MySampleApp\Package.json
MySampleApp\Server.js
MySampleApp\public:
index.html - Invoked when server.js starts and shows "Click Me" button
fetchprocess.js - check button click and then show in DocumentElementID
user1.ps1 - runs Get-Process command to fetch processes
fetchprocess.js:
console.log('Client-side code running');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
console.log('button was clicked');
document.getElementById('counter').innerHTML = "ClickedNow";
var ps = new shell({
executionPolicy: 'bypass',
noProfile: true
});
app.get("/", function (req, res) {
ps.addCommand("./user.ps1", [ {
name: 'guid', value: req.params.guid
} ])
ps.invoke().then(output => {
res.end(output); // This is to show the output in web browser
})
})
});
Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<p id="counter">Loading button click data.</p>
<button id="myButton">Click me!</button>
</body>
<script src="fetchprocess.js"></script>
</html>
My objective is to execute "user1.ps1" when someone clicks on the "ClickMe" button and then show the data in HTML Div (Counter). When I try to run above code it throws an error that require is not defined in fetchprocess.js file.
Image:
I will have several scripts under the public folder that will be executed when someone clicks on other buttons on the web app. What is the best folder structure for such project.
Thank you very much

TL; DR; There is no way you can execute Node.js code in a browser.
Looks like you messaged up with libraries. You are trying to execute some Node.js code in the browser.
<script src="fetchprocess.js"></script>
Here you are loading the script in the browser. The truth is that Browser JS code does not have access to the platform things like PowerShell and it is not Node.js at all. If you need to execute Node.js code use Node.js executable.
UPD:
The workaround may be the following.
Spin up HTTP server locally with Node.js
Add an endpoint that runs the PS script once it receives a request.
On-click send AJAX request to your server.
But it worth noticing that it will work only on the machine where the Node.js server is running. Because it is not possible to run PowerShell from a browser.

Related

Newby: index.js file doesn't work in index.html file

I'm new in Javascript world, currently I'm trying to implement a GUI using electron js framework.
Trying to reproduce the code from a tutorial, I got stuck on a code which seems not to work on my PC, basically even if I click on a button, the console is not logging anything (when it should have!!); the aim of the code is to refer to a button defined in an index.html file from a index.js containing the script and log a sentence when the button is clicked, but it seems like the script in the html file cannot access the .js file at all. Here I'm reporting the code from index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>my-app</title>
<link rel = "stylesheet" href="styles.css">
</head>
<body>
<button id = "button1" > START </button>
<script>
require('./index.js');
</script>
</body>
</html>
Here the code belonging to index.js file:
const electron = require("electron");
const button1 = document.getElementById("button1");
button1.addEventListener("click", startApp);
function startApp(){
console.log("Button clicked!");
};
Note:
I've tried to debug this code based on my very little knowledge of Javascript and electron:
I used document.getElementById("button1"); in index.html and it does work (the variable obtained was used to change button text color), but the same is not working when reported in the index.js file;
I tried console.log("In index.js"); in index.js but still it is not working!
From these results I thought the problem may be the .html and .js file communication; they are in the same folder. One more thing: I downloaded the tutorial code from GitHub and the problem is still present with the same actions at points 1 and 2.
Edit: I've omitted that I'm linking index.html window and displaying it in the main.js file, in fact the windows does show up, but the the click on the button doesn't produce any action.
Seemed to be a problem with the require module not working in .html file.
Solved by replacing it with <script src="index.js"></script>.
It appears that you shoud be using electron to load the index.html via BrowserWindowonce it is ready. app and BrowserWindow are from the electron module.
`const { app, BrowserWindow } = require('electron')`
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
})
From the quick start
In Electron, browser windows can only be created after the app module's ready event is fired. You can wait for this event by using the app.whenReady() API. Call createWindow() after whenReady() resolves its Promise.
For futher info see https://www.electronjs.org/docs/tutorial/quick-start
Hope this proves useful.

How to run Python script from Javascript on Apache web server?

Cannot get HTML file to call JavaScript function hello() on Ubuntu Apache 2. I have seen similar problems where the solution was to uncomment the #JSDIR line on the httpd.conf file but there is now only apache.conf and no similar line. I want to call the python script accesstest.py to write the current date and time to a text file from the main.js function after clicking the button on the HTML file. All of the files work correctly when run separately. How do I fix this?
index.html HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title><demo</title>
</head>
<body>
<h1></h1>
<script src="main.js"></script>
<button onclick="hello();">js function</button>
</body>
</html>
main.js JavaScript code:
let myHeading = document.querySelector('h1');
myHeading.textContent = 'Hello world!';
function hello(){
var spawn = require("child_process").spawn;
var process = spawn('python,["accesstest.py"]);
alert('hello');
}
accesstest.py Python code:
import datetime
def execute():
file = open('/path/to/file/pytest.txt', 'a+')
file.write('test time: %s \n' % (datetime.datetime.now()))
file.close()
execute()
Here is the display:
page displays "Hello World!" with "js function button" that does nothing
Here are a couple solutions I found that didn't work for me:
Unable to call JavaScript function in html on button click
How to link external javascript file onclick of button
Thanks.

HTML Button to call app.quit() function using electron

I recently discovered electron as a GUI "maker". I asked my programming-teacher, if it's possible to run a bash script with electron.
He gave me a link to a GitHub (sadly bought by Microsoft) and it worked with a bash-script
I recently wrote a script, which installs the Origin Launcher using wine and it workd perfectly. But now, I wanted to try to cover it with a GUI, so people who aren't familiar with the Linux Terminal have a nice-looking GUI.
Now, I watched a video on how to create an electron app. I followed it step by step, and it worked.
In my index.html document, I made two buttons, one to start the Installation, and the second one to cancel it.
I included the main.js in the head part of the html File
<head>
<title>LoriginSetup</title>
<link href="assets/css/main.css" rel="stylesheet">
<script src="main.js"></script>
</head>
And inside the Body, I used the onclick to call the function inside the main.js.
The Function is called quitApplication()
<div class="btns">
<button class="btn btnstart" id="startinstall">Start Installation</button>
<button class="btn btncancel" id="cancelinstall" onclick="quitApplication()">Cancel Installation</button>
</div>
I tested the Function using an alert('').
The alert is working fine, but as I replaced the alert with app.quit(); It didn't work anymore.
app.on('ready', function(){
//Create new window
mainWindow = new BrowserWindow({});
//Load html into window
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file',
slashes: true
}));
//Build Menu from MenuTemplate
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
//Insert Menu
Menu.setApplicationMenu(mainMenu);
});
function quitApplication(){
alert('This Button is Working');
}
I don't know what I made wrong, but I appreciate every help I could get.
Remove quitApplication() from the main Electron JS and add this in your main.js :
const electron = require('electron');
const remote = electron.remote;
function quitApplication(){
if (process.platform !== 'darwin') { remote.app.exit(); }
}
Another way, if you want to keep this code in the main Electon JS file, is to use IPC : https://electronjs.org/docs/api/ipc-main . The renderer can call a method in the main process which quits.

Create a button to execute a .bat or .exe

I'm a newbie with Electron and JS.
I've searched for a solution to create a simple button which executes a .bat file or .exe file.
I've read this article about using child_process.
However, It doesn't say how to "link" var to my button.
My code is written in renderer.js
electron runs using nodejs therefore you could do something along the lines of:
var execFile = require('child_process').execFile;
var runExe = function(){
execFile('<your-name>.exe', function(err, data) {
console.log(err)
console.log(data.toString());
});
}
now call
runExe()
using your button and you should be good to go
for more info see here
node js reference
so what happens is basically that we run a specified exe file using like you already said the nodejs child_process ... hope that helped
Ok, Now is work i post my solution for electron:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<!-- All of the Node.js APIs are available in this renderer process. -->
We are using Node.js <script>document.write(process.versions.node)</script>,
Chromium <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
<h1> A simple Javascript created button </h1>
<button onclick="function()">Firefox 1</button>
<button onclick="firefox()">Firefox 2</button>
<script>
var execFile = require('child_process').execFile;
function firefox(){
execFile("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe", function(err, data) {
console.log(err)
console.log(data.toString());
});
}
// You can also require other files to run in this process
require('./renderer.js')
</script>
</body>
</html>

Problems with SkyScanner Widget in webpage

I am following this example to include a SkyScanner widget on my website:
http://business.skyscanner.net/portal/en-GB/Documentation/Widgets
For some reason I just get an empty div - could this be something to do with the key? When I clicked on the activation link I got from SkyScanner for the widget key, I got a page saying the following:
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be
viewable on remote machines, please create a tag within
a "web.config" configuration file located in the root directory of the
current web application. This tag should then have its
"mode" attribute set to "Off".
I have created a web.config file with the following code:
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
I've had a look at 'inspect element' on Chrome and get the error
Uncaught TypeError: Object # has no method 'write'
api.ashx?key=[KEY]:1
This is the JS:
var API_KEY = 'b7290ac3-1f9f-4575-88a7-89fed0c61f7f',
MAIN_URL = 'http://api.skyscanner.net/api.ashx?key=' + API_KEY;
function main(){
console.log('loaded module');
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
};
function newWrite(str) {
$(str).appendTo('body');
}
var oldWrite = document.write;
document.write = newWrite;
function onMainSkyscannerScriptLoad(e) {
console.log('loaded main script');
skyscanner.loadAndWait('snippets', '1', {'nocss' : true}, main);
}
$('button').click(function() {
console.log('getting main script');
$.getScript(MAIN_URL, onMainSkyscannerScriptLoad);
});
I also used this to personalise the widget:
skyscanner.load("snippets","2");
function main(){
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setShape("box300x250");
snippet.setCulture("en-GB");
snippet.setCurrency("USD");
snippet.setColourScheme("classicbluelight");
snippet.setProduct("flights","1");
snippet.setProduct("hotels","2");
snippet.setProduct("carhire","3");
snippet.draw(document.getElementById("snippet_searchpanel"));
}
skyscanner.setOnLoadCallback(main);
Skyscanner B2B support engineer here. Are you still having trouble with this?
For the quickest response, please contact us here: http://business.skyscanner.net/portal/en-GB/Home/Contact
The first thing to check is that the file is on a web server (localhost is fine), and not loaded from the desktop (or local disk in general). This is because some of the Skyscanner JS code looks up other files using URLs like //api.skyscanner.net. In other words, saving the file to the desktop and opening it from there will not work (will show as an empty div). Here's the most basic example of drawing a widget. Can you try putting this in a file and accessing it through a server? If it works we can build on it :)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="//api.skyscanner.net/api.ashx?key=b7290ac3-1f9f-4575-88a7-89fed0c61f7f"></script>
<script type="text/javascript">
skyscanner.load("snippets","2");
function main(){
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setShape("box300x250");
snippet.setCulture("en-GB");
snippet.setCurrency("USD");
snippet.setProduct("flights","1");
snippet.setProduct("hotels","2");
snippet.setProduct("carhire","3");
snippet.draw(document.getElementById("snippet_searchpanel"));
}
skyscanner.setOnLoadCallback(main);
</script>
</head>
<body>
<div id="snippet_searchpanel" style="width: auto; height:auto;"></div>
</body>
</html>

Categories