Executable run from electron project isn't loading resources - html

I am making a electron application that launches an executable stored on my computer when run. If I run the exe by itself, it works correctly and loads all of the fonts. However, when run by the electron app, it opens, but non of the font files can be loaded. The exe is a compiled release project made in visual studio.
I tried putting the res folder into the same directory as index.html to no avail.
Code for index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<script>
var child = require('child_process').execFile;
var exePath = "C:\\Users\\name\\Documents\\Visual Studio 2015\\Projects\\Ten\\Release\\Ten.exe";
var parameters = ["test"];
child(exePath, parameters, function(err, data){
console.log(err);
console.log(data.toString());
})
</script>
</body>
</html>
Code for main.js
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
win = null
})
}
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
Thanks!

Does your exe use a relative path to load the fonts? If so, either change the exe to be more flexible, or in your call to execFile() specify the optional 3rd arg to specify the desired working directory.
var child = require('child_process').execFile;
var exePath = "C:\\Users\\name\\Documents\\Visual Studio 2015\\Projects\\Ten\\Release";
var exe = exePath + "\\Ten.exe";
var parameters = ["test"];
var options = {cwd:exePath};
child(exePath, parameters, options, function(err, data){
console.log(err);
console.log(data.toString());
});
If that doesn't work, my guess would be some kind of permissions problem. Is your electron app running as a different user to when you test the exe?

Related

Read static files with express got "Cannot Get /"

I tried to learn how to read static files with express from a reliable website. And then I found that not know why, my terminal tell me I'm success but website show me "Cannot Get /"(as following image show). I had found a lot of solution (e.g. in my html file, I add script src to socket.io) but still fail. Where can I start to deal with it? Please help me...
terminal show success
website show error
And the following is my code:
C:\...\1-on-1-webrtc\server.js
const express = require('express')
const app = express()
const http = require('http').createServer(app)
// static data
app.use('/', express.static(__dirname + '/public/'))
// TODO: Signaling
//start server listen 8080 port
http.listen(8080, () => {
console.log(`Server running in 8080`)
})
C:\...\1-on-1-webrtc\pubilc\index.html
(origin)
"hello"
(after)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>111</title>
<script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
var socket = io();
</script>
</body>
</html>
I change Your code a little and here is my solution:
Firstly change your name of public folder to correct. Not "pubilc" only "public".
Folder & File Structure:
server.js :
const express = require("express");
const app = express();
const port = 8080;
// const http = require("http").createServer(app);
// static data
app.use("/", express.static(__dirname + "/public"));
//start server listen 8080 port
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
index.html (without any changes) :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>111</title>
<script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
var socket = io();
</script>
</body>
</html>
Output :
Tested with: express 4.17.2 node 16.13.0 Linux Ubuntu 20.04 and Win10

Send data from SerialPort to socket.io

I'm struggling with socket.io, express, and node.js.
I send data from an Arduino to my cmd. This is done with the serialport libary. But now I want this data displayed on my web browser. I'm using the express library for this. I have index.js here is the connection with the arduino and browser. And an index.html
This code do I have:
code from index.js (node.js server):
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
port = 8888;
//Server start
server.listen(port, () => console.log('on port' + port))
//user server
app.use(express.static(__dirname + '/public'));
io.on('connection', onConnection);
var connectedSocket = null;
function onConnection(socket){
connectedSocket = socket;
}
//Arduino to CMD
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const usbport = new SerialPort('COM4');
const parser = usbport.pipe(new Readline());
parser.on('data', console.log);
The data what is recieved from the serialport (Arduino), had to be displayed in the index.html (webbrowser). I tried already something but it doesn't work. It has to be printed in the <p></p> in the html code.
The index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="text">
<p></p>
</div>
<script>
var text = document.getElementById('text');
var socket = io.connect('http://localhost:8888');
socket.on('data', function(message) {
text.innerHTML = message.data;
});
</script>
</body>
</html>
Instead of
parser.on('data', console.log);
Try this:
parser.on('data', function (data) {
io.emit('data', { data: data });
});
That should send the parsed data from the SerialPort to the socket, which should end up on the client side on the website.

Cannot get on http://localhost:3000/

I am using gulp.The tasks are getting run creating required folders. But I get Cannot GET/ error when run in browser.I have attached the image of my project structure and also the output in command line. .My index.html contains the following
<!DOCTYPE html>
<html lang="en" ng-app="helloWorldApp">
<head>
<title>Angular hello world app</title>
<link href="css/main.css" rel="stylesheet">
</head>
<body>
<ng-view class="view"></ng-view>
</body>
<script src="js/scripts.js"></script>
</html>
I want to know why it cannot get or not routed properly and what should be done. So the problem is when the server is running on localhost and I hit localhost:3000/ in browser it says cannot get with a white background.Following is my gulpfile.js
const gulp = require('gulp');
const concat = require('gulp-concat');
const browserSync = require('browser-sync').create();
const scripts = require('./scripts');
const styles = require('./styles');
var devMode = false;
gulp.task('css',function(){
gulp.src(styles)
.pipe(concat('main.css'))
.pipe(gulp.dest('./dist/css'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('js',function(){
gulp.src(scripts)
.pipe(concat('scripts.js'))
.pipe(gulp.dest('./dist/js'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('html',function(){
gulp.src('./templates/**/*.html')
.pipe(gulp.dest('./dist/html'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('build',function(){
gulp.start(['css','js','html']);
console.log("finshed build");
});
gulp.task('browser-sync',function(){
browserSync.init(null,{
open : false,
server : {
baseDir : 'dist'
}
});
console.log("finshed browser ");
});
gulp.task('start',function(){
devMode = true;
gulp.start(['build','browser-sync']);
gulp.watch(['./css/**/*.css'],['css']);
gulp.watch(['./js/**/*.js'],['js']);
gulp.watch(['./templates/**/*.html'],['html']);
});
Since your baseDir is 'dist' you need to run http://localhost:3000/html in the browser I think that should work.
You need to point browserSync to the dist/html/index.html file as the start page with index.
gulp.task('browser-sync',function(){
browserSync.init(null,{
open : false,
server : {
baseDir : 'dist',
index : "html/index.html"
}
});
console.log("finshed browser ");
});

Ionic 2, Chrome keeps loading from disk cache

I'm developing a mobile app and use the following command to build and run a version that works in a browser (pulling in all necessary hooks, which ionic serve does not)
ionic build browser --desktop --testing && http-server platforms/browser/www/
Yesterday, and for weeks, this works perfectly. I stop and start that same command, it builds/compiles everything, everything is great.
Then I updated Google Chrome. Now, no matter what I do, Chrome keeps pulling all of these resources from disk cache, even after I delete and re-create them. Any ideas how I can solve? I don't want to have to clear my cache out every time I reload, and it seems this'll cause additional issues down the road.
I don't know why or how this changed, no project or config settings are different in my Ionic2 app.
Using cmd-shift-R instead of just cmd-R to reload seems to force Chrome to not load from disk cache but I'm confused and want to understand what happened here...
Chrome caches a lot but you can force it to load resources from your server instead of taking them out of cache by using cache busting:
Load templates:
var timestamp = (new Date()).getTime();
$ionicPopup.show({
scope: $scope,
title: 'Work!',
templateUrl: '/templates/roll-timer-popup.html?update='+timestamp
});
Load scripts/stylesheets:
<script src="myscripts.js?update=123..."></script>
<link rel="stylesheet" type="text/css" href="theme.css?update=123...">
For script/stylesheets you might create them along with the timestamps dynamically and insert them afterwards.
Or when your scripts-files get bundelt together, you could use a script to write timestamps into your finally index.html file for deployment by using a nodejs-script, for I made this script for one of my projects:
const fs = require('fs');
var filename = process.argv[2];
var regExp = /[.|\w]+[.]js/;
var contentToAttach = ['<!-- CONTENT ATTACHED BY '+process.argv[1]+' -->','you can put other content in here that is put into at the end of your file'];
fs.readFile(filename, {
flag : 'r',
encoding: 'utf-8'
},(err, oldFileContent) => {
if (err) throw err;
var fileContent = oldFileContent;
var oldScriptName;
var now = (new Date()).getTime();
var lastIndexPos = 0;
while (oldScriptName = oldFileContent.match(regExp)) {
var newScriptName = oldScriptName + '?update=' + now;
var newIndexPos = fileContent.indexOf(oldScriptName);
if (newIndexPos !== lastIndexPos) {
fileContent = fileContent.replace(oldScriptName, newScriptName);
lastIndexPos = newIndexPos;
}
else {
// same filename found
var fildContentSlice = fileContent.slice(newIndexPos+oldScriptName.length);
fildContentSlice = fildContentSlice.replace(oldScriptName, newScriptName);
fileContent = fileContent.slice(0,newIndexPos+oldScriptName.length)+fildContentSlice;
}
oldFileContent = oldFileContent.replace(oldScriptName, '');
}
var wholeContent = fileContent+'\n\r'+contentToAttach.join('\n\r');
fs.writeFile(filename,wholeContent, (err) => {
if (err) throw err;
console.log('File: '+filename+' is updated!');
});
});
It inserts ?update=123... in every script-tag it can find in a file.
To execute this script in the shell write:
node updateScript.js path_to_your_html_file
Hope it helps.

I receive a GET error when trying to serve html page with image using Node.js

I am new to Node.js and am unable to find a way to solve my issue. I have written a server using Node.js to serve a html webpage. The problem is that it wont display the images that are in the same folder. I am trying to serve my webpage as well as my images and css file. Any help would be appreciated.
Relevant code:
server:
var http = require('http');
var fs = require('fs');
const PORT = 8080;
function handleRequest(request, response) {
console.log(request.url);
var bool = 0;
var index = fs.readFileSync("index.html", {
encoding: "utf-8"
});
if(request.url == "/")
{
bool = 1;
response.end(index);
}
else if(request.url == "/index" || request.url == "/index.html")
{
bool = 1;
response.end(index);
}
else if(bool == 0)
{
response.statusCode = 404;
response.end("Not Found");
}
}
var server = http.createServer(handleRequest);
server.listen(PORT, function() {
console.log("Started server on http://localhost:%s", PORT)
});
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Personal Webpage</title>
<link rel="stylesheet" href="index-css.css"/>
</head>
<body>
<h1>Welcome!</h1>
<p>My paragraph.</p>
<img src="/family.jpg" alt="Family" style="width:342px;height:513px;">
<img src="/Another.jpeg" alt="Another" style="width:500px;height:500px;">
</body>
</html>
I recommend use app.use(express.static(__dirname + '/FOLDER_NAME')) in order to expose a folder to serve static files to the client. Here is the documents about serving static files using express.
Edit: Here is a simple working example of serving a index.html using express
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});