electron app.getpath('exe') result is not what I expected - node.js

I want to start my app automatically on system startup.
I used auto-launch.
var AutoLaunch = require('auto-launch');
var autoLauncher = new AutoLaunch({
name: "App name",
path: app.getPath('exe'),
});
console.log(`app path : ${app.getPath('exe')}`)
//result : C:\Users\USER-PC\project_folder\dist\electron.exe
autoLauncher.isEnabled().then(function(isEnabled) {
if (isEnabled) return;
autoLauncher.enable();
}).catch(function (err) {
throw err;
});
The problem is, I am using electron-builder for building an exe file. And when I build an exe file its name is like : 'app-name 1.0.0.exe'.
So auto launch is not working properly because the option, 'path' is different from the actual exe file's path.
How can I solve this?
I tried to set the app name so app.getPath('exe') can return the actual .exe path. But it did not work.
app.setName('app-name')

Related

App launched from npm works perfectly, but complied x64 app works incorrect

I use the Electron-forge framework and try to make an audio player. When I launch my app from npm start it works perfectly. But when I compile app using npm run package to x64 app and launch from its .exe file, the app works incorrectly. Window creates, but audio doesn't play.
Error in console.log:"Uncaught (in promise) DOMException: Failed to load because no supported source was found."
Paths to audio files are definitely correct, I wrote them to console too.
Edit: I found it is better to use Promise for tag audio, but the problem still persists. Code:
$(document).ready(function () {
prepare_song('D:' + '\\' + 'Downloads' + '\\' + 'audio_1.mp3');
$("#button_play_pause").click(function () {
console.log("click play");
var playPromise = document.querySelector('audio').play();
if (playPromise !== undefined) {
playPromise.then(function () {
console.log("play !");
// triggered from npm start and music is playing
}).catch(function (error) {
console.log("play error:" + error);
// triggered from npm run package (x64 .exe app) Error: NotSupportedError: The element has no supported sources.
});
}
});
});
function prepare_song(filepath) {
console.log(" prepare: " + filepath);
$("#audio").attr("src", filepath);
let audio = document.getElementById('audio');
audio.load();
}

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)://...

reading a packaged file in aws lambda package

I have a very simple node lambda function which reads the contents of packaged file in it. I upload the code as zip file. The directory structure is as follows.
index.js
readme.txt
Then have in my index.js file:
fs.readFile('/var/task/readme.txt', function (err, data) {
if (err) throw err;
});
I keep getting the following error NOENT: no such file or directory, open '/var/task/readme.txt'.
I tried ./readme.txt also.
What am I missing ?
Try this, it works for me:
'use strict'
let fs = require("fs");
let path = require("path");
exports.handler = (event, context, callback) => {
// To debug your problem
console.log(path.resolve("./readme.txt"));
// Solution is to use absolute path using `__dirname`
fs.readFile(__dirname +'/readme.txt', function (err, data) {
if (err) throw err;
});
};
to debug why your code is not working, add below link in your handler
console.log(path.resolve("./readme.txt"));
On AWS Lambda node process might be running from some other folder and it looks for readme.txt file from that folder as you have provided relative path, solution is to use absolute path.
What worked for me was the comment by Vadorrequest to use process.env.LAMBDA_TASK_ROOT. I wrote a function to get a template file in a /templates directory when I'm running it locally on my machine with __dirname or with the process.env.LAMBDA_TASK_ROOT variable when running on Lambda:
function loadTemplateFile(templateName) {
const fileName = `./templates/${templateName}`
let resolved
if (process.env.LAMBDA_TASK_ROOT) {
resolved = path.resolve(process.env.LAMBDA_TASK_ROOT, fileName)
} else {
resolved = path.resolve(__dirname, fileName)
}
console.log(`Loading template at: ${resolved}`)
try {
const data = fs.readFileSync(resolved, 'utf8')
return data
} catch (error) {
const message = `Could not load template at: ${resolved}, error: ${JSON.stringify(error, null, 2)}`
console.error(message)
throw new Error(message)
}
}
This is an oldish question but comes up first when attempting to sort out whats going on with file paths on Lambda.
Additional Steps for Serverless Framework
For anyone using Serverless framework to deploy (which probably uses webpack to build) you will also need to add the following to your webpack config file (just after target: node):
// assume target: 'node', is here
node: {
__dirname: false,
},
Without this piece using __dirname with Serverless will STILL not get you the desired absolute directory path.
I went through this using serverless framework and it really was the file that was not sent in the compression. Just add the following line in serverless.yml:
package:
individually: false
include:
- src/**
const filepath = path.resolve('../../filename.text');
const fileData2 = fs.readFileSync(process.env.LAMBDA_TASK_ROOT + filepath, 'utf-8');
I was using fs.promises.readFile(). Couldn't get it to error out at out. The file was there, and LAMBDA_TASK_ROOT seemed right to me as well. After I changed to fs.readFileSync(), it worked.
I hade the same problem and I tried applying all these wonderful solutions above - which didn't work.
The problem was that I setup one of the folder name with one letter in upper case which was really lowercase.
So when I tried to fetch the content of /src/SOmething/some_file.txt
While the folder was really /src/Something/ - I got this error...
Windows (local environment) is case insensitive while AWS is not!!!....

fs.open fails with file extension - node.js

I've got the following code:
fs.open("uploads/test.txt", "a", "0755", function(err, fd){
if(err) { console.log(err); }
else {
file.handler = fd; //We store the file handler so we can write to it later
...
}
});
The file is created and written to perfectly when I simply have "uploads/test", but when I try to do "uploads/test.txt" it breaks. Any ideas?
I think you should try using
var path = './uploads/test.txt'.
Or
var path = __dirname + 'your_path';
fs.open(path, "a", "0755", function(err, fd){
if(err) { console.log(err); }
else {
file.handler = fd; //We store the file handler so we can write to it later
...
}
});
This is really silly, but I found what was causing my code to break:
fs.open works as intended. The bug was with my file detection setup using nodemon.
The reason is everytime my app would load it would run the above mentioned code. The code would then write to a new file in my apps /uploads directory. Nodemon would then detect the new file and restart the app thus creating a vicious circle.

trying to access and manipulate images with node.js and GD or imagemagick

i'm trying to create a thumbnail of an jpg that resides on the server. i tried using node-gd and/or node-imagemagick but neither could access the file:
var gd = require('node-gd');
gd.openJpeg("./test.jpeg", function (img, path) {
if (img) {
console.log("file opened ... " + img);
}
else {
console.log("failed to open file ...");
}
});
logs: failed to open file ...
imagemagick:
var im = require('imagemagick');
im.identify('./test.jpeg', function (err, features) {
if (err) throw err;
console.log(features);
});
logs: Error: Command failed: execvp(): No such file or directory
but the test.jpeg file is definitely there.
var fs = require('fs');
fs.open(filePath, 'r', function (err, fd) {
console.log("open file ... " + err + " " + fd);
});
works fine!? no error is logged.
i tried chmod 0777 on the jpeg. nothing.
From what I understand of the documentation of the imagemagick module for node is, that the module provides access to the comandline binaries of imagemagick. Do you have imagemagick (the commandline binaries) installed? Are they in the PATH of you shell?
You are looking for a binary named "identify". You can show the path to it by running "which identify". It should give you a full path - if the prompt just returns, you don't have it installed or it's not in your path.
If you are on win32 the which command won't help, you have to check for a binary called identify.exe.
(never worked with gd - so I am unsure there)
here is the imagemagick example with your code - please note, the path to identify may be different in your environment:
snowflake:Desktop rhaen$ node check_im.js
{ format: 'JPEG', width: 320, height: 250, depth: 8 }
snowflake:Desktop rhaen$ which identify
/usr/local/bin/identify
So - the node module and your code works for me.

Resources