Learning Electron I'd like to do some file processing after a drag and drop. On a Mac the equivalent for tmp is a $TMPDIR. Referencing the API documentation of app I was able to locate the app.getAppPath() which shows my path from a simple console log from main.js. Below app.getAppPath() there is getPath() but when I try app.getPath(temp):
let foobar = app.getAppPath("temp")
console.log(foobar)
I get an error in the console of:
ReferenceError: temp is not defined
Through my research I've read:
How to store user data in Electron
How to get the original path of a portable Electron app?
Creating and Using Temporary Files
Get Special folder Path in Electron
electron temp directory
How to set a custom path for Electron app installer
In Electron is there a built-in for the temp directory to work on all operating systems or a process to reference?
Note:
Even after referencing the string of:
console.log(`The temp path is: ${app.getAppPath("temp")}`)
it returns the same response as:
console.log(`The AppPath is: ${app.getAppPath()}`)
which is:
The temp path is: /Users/Grim/Documents/GitHub/electron-quick-start-boilerplate
The AppPath is: /Users/Grim/Documents/GitHub/electron-quick-start-boilerplate
and the above console.log tests have been added after letWindow.
app.getAppPath() doesn't take an argument.
For app.getPath(name), the argument should be the string "temp": app.getPath("temp").
Related
I am looking to access a JSON config file that the user would place next to their package.json from a node_module package that I created. Is there a best approach to do this. I tried a relative import but that didn't really work and I am not sure how best to accomplish dynamic imports if the config file doesn't exist because I want to allow it to not exist as well.
Here is how I tried to handle dynamic imports though:
export const overrides = (function () {
try {
return require('../../../../../../overrides.json');
} catch (_err) {
return null;
}
})();
Also I tried fs but I get a browser config error I am not sure if that is something else. I should research but I didn't understand the docs around that.
using a library
This worked for me: find-package-json
Basically on any js file who needs the base, home or workspace path, do this:
var finder = require('find-package-json');
var path = require('path');
var f = finder(__dirname);
var rootDirectory = path.dirname(f.next().filename);
rootDirectory will be the location of the folder in which the main package.json exist.
If you want to optimize, get the appRootPath variable at the start of your app and store/propagate the variable to the hole nodejs system.
no libraries
Without any library, this worked for me:
console.log("root directory: "+require('path').resolve('./'));
This will get you the root directory of your nodejs app no matter if you are using npm run start or node foo/bar/index.js
More ways to get the root directory here:
Determine project root from a running node.js application
usage
If you achieve to obtain the root directory of your nodejs app and your file is at the package.json level, use this variable like this to locate any file at root level:
rootDirectory+"/overrides.json"
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
This is the code for my app (index.js) . It uses a file named config.json using a relative path ./config.json. When I compile this into my mac using $pkg index.js, I obtain a test-macos file that is my app. Both the app and the config.json file are located in the same folder named project (this is why I can use the relative path ./config.json). However, once runnning the app I run into an error:
/Users/amelie/Documents/project/test-macos ;
exit; internal/fs/utils.js:312
throw err;
^ Error: ENOENT: no such file or directory, open './config.json'.
Therefore it seems that my app cannot find the config.json file. I could determine an absolute path but I need these two files to always be together because I need the path in the variable
var obj = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
to be always the same since I share those files to other people and the absolute path would therefore change. Is there a way to do this ?
I have a Node.js project which must be integrated with a previously written Python script. Currently Node.js project is deployed in such a way that the Python script must be placed inside of the Node root directory. Under these conditions the whole project runs well and there are no error warnings. For some reasons, I would like to put the Python script outside of the Node root directory. Thus, I have added .cwd parameter:
const python = pythonBridge({
python: 'python3',
stdio: ['pipe', 'pipe', 'pipe'],
cwd: '/dir1/dir2/' # added line
})
Now when the Python script is inside of /dir1/dir2/ folder, an error message is generated:
ERROR: (node:14870) UnhandledPromiseRejectionWarning: ReferenceError: logger is not defined
at /NodeJSrootFolder/dist/NodeJSFactory.js:69:7
Being a newcomer in Node.js, I would like to know besides .cwd which parameters must be changed in order to make project run correctly?
According to the instructions posted here (https://www.npmjs.com/package/python-bridge), current working directory of the child process must be specified via .cwd option:
var python = pythonBridge(options)
options.cwd - String Current working directory of the child process
As I have mentioned in my question, this solution doesn't work. Actually, .js file ignore .cwd option and looks for the Python script inside of the Node.js root directory. In order to resolve the problem, the full address must be specified inside of the FS object:
const fs = require('fs').promises
// ...
// somewhere below
// ...
let reads = [
fs.readFile('/dir1/dir2/myPythonScript.py'),] // vs. fs.readFile('./myPythonScript.py')
I am not sure whether it is a normal procedure or some dirty hack, but it works for my project.
Problem loading a file using relative path when my node app is initialised using a another node app
I have created an npm which relies on a file stored relative to project root. something like this
index.js
- res
- config.json
Now I read the config.json using following code
const pathToConfig = path.resolve(__dirname, '../res/config.json')
This works great locally.
But in my prod setup this app is initialised by another node app.
And __dirname resolves to root of that app so all my logic to find config.json get messed up.
Is there any way I can read the file without worrying about how node app was initialised?
Have you tried the command process.cwd()? It is almost the same as __dirname but does differ slightly.
I am creating an electron app and packaging for distribution with electron-builder for windows and Mac. This app creates a folder and some pdfs inside varying based on user input. The pdfs also use an image, which as a node app I was keeping in the root folder of the app.
I managed to write to the desktop using an absolute path.
if (!fs.existsSync(`/Users/${user}/Desktop/2019 Certificates`)){
fs.mkdirSync(`/Users/${user}/Desktop/2019 Certificates`);
}
but when I use this relative path
stampandseal.png
I get the following error:
I expect it to find the png relative to the js file, however I get the following error:
fs.js:121 Uncaught Error: ENOENT: no such file or directory, open 'stampandseal.png'
If I understand your issue correctly, you are trying to copy an image from within the app bundle to the user's desktop. Use __dirname to reference the directory your code is executing in, and then build the path off of that.
The code below is used by my main.js file, which is in the directory containing my app directory. I use upath to build the path and jetpack instead of fs for copying
var fromPath = upath.join(__dirname, "app", "assets", "image.png");
jetpack.copy(fromPath, toPath, { overwrite: true });