How to save/write a file from html with javascript? - javascript

I am doing an easy desktop app to crop photos, in order to do this I have a npm project with a few dependencies and an HTML file and launch the browser with the following command, chromium-browser --disable-web-security.
The problem is that when the app execute this code:
crop(event) {
cropper.getCroppedCanvas().toBlob((blob) => {
saveAs(new Blob([blob] ), './a.jpg');
});
And this download automatically the file in the download folder instead of the same folder where the index file is.
Any idea about how can I set a relative path to download the file?
Thanks.

If you are just targeting chrome, there is a way. You can use Chrome's FS functionality
https://web.dev/file-system-access/
If you first load the file using this API, you will have the FileHandler object to use when you want to save

Related

How to define the HTML file extension in Visual Studio?

My project does not recognize the css and other files in the html files I have created, although I have written the extension paths correctly. How can I fix?
First of all you need to configure serving static files in Startup
app.UseStaticFiles(); //serves wwwroot by default
To serve your theme folder you need to add the following lines
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "theme")),
RequestPath = "/theme"
});
You did not put the correct path there. Your "style.css" is in 'theme/src/style.css' not in the 'theme/style.css'. Also use VS Code not Visual Studio because is useless if you create just files.
Also you did not provide all the files that are in the JS folder and CSS folder.

Electron: Store user editable data in .txt file

I am making an electron app that converts data from .txt files to Javascript arrays. This data is stored inside a folder called faces in the main directory. I also have a button in my app which, when clicked opens file explorer at the faces folder so the user can edit the .txt files. This works fine when running npm start, but then when I use electron builder to package my app, the app can no longer find the .txt files and the user cannot edit them (giving me lots of errors). Is there some way to have a folder of .txt files that the app uses to draw information from with Electron builder?
Edit
Below is the JS used:
//Import Lists from .txt files
var ears = fs.readFileSync('faces/ears.txt', 'utf8').split('\n');
var mouths = fs.readFileSync('faces/mouths.txt', 'utf8').split('\n');
var eyes = fs.readFileSync('faces/eyes.txt', 'utf8').split('\n');
//Opens faces txt docs in file explorer
function edit() {
shell.openItem(require('electron').remote.app.getAppPath() + '/faces')
}
Here is what happens when I open the packaged app (this is the win-unpacked result but the error is the same for .exe which runs with the installer):
As you can see it does not load an information and you can see it cannot find the faces folder or the .txt files.
I think the problem is that the path-joining character is different in each OS.
You can see that every slash was backslash(\) before your suffix, /faces.
Try using path module.
const path = require(path)
....
function edit() {
shell.openItem(
path.resolve(require('electron').remote.app.getAppPath(), 'faces')
)
}
The builded app is trying to write in the app folder itself. This is possible in dev, but not in production since che app became an asar archive. (app.asar). If you look at the error your app is trying to write inside app.asas, which is not a folder. So it's not possible to write inside it.
You probably want to save these kind of information not in the path where the application has been installed, but in some of the paths related with user config/preferences.
This: https://www.electronjs.org/docs/api/app#appgetpathname may help you retrive the right path.

How to download the complete project structure from cdnjs using Python

I want to download the complete project from the cdnjs cloud to local folder.
I have tried this:
import requests
files = requests.get("https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML%2CSafe.js&ver=4.1")
with open("mathjax.js","w") as file:
file.write(files.text)
Now this download the js file. When I tried using the same code to get the project instead of the js file, the output was weird.
So I tried using the cdnjs and check what happens when I use cdnjs cloud and when I use local file.
I have got this difference as shown in the images:
Using cdnjs:
Using Local file:
How I can get the similar structure as I get when I use cdnjs?
Kindly, advise me.
The URL you are providing to requests module is just the URL of one file MathJax.js, that is why you are getting only that file as output.
What you want is to download the complete directory mathjax/2.7.5/. However, if we request the whole directory, the server forbids such requests.
An alternate approach is to get relative paths of all the files from the main directory, which you already have as you showed in image. You can then download each of the file independently and store it into its respective folder. You'll have the whole directory ready at the end.
Try the following code for this purpose.
import requests
import os
baseUrl="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/" #Base URL for the main directory
#List containing relative paths of all required files
relativePaths=['config/Safe.js?V=2.7.5',
'config/TeX-AMS-MML_HTMLorMML.js?V=2.7.5',
'extensions/Safe.js?V=2.7.5',
'jax/output/SVG/fonts/TeX/fontdata.js?V=2.7.5',
'jax/output/SVG/jax.js?V=2.7.5',
'MathJax.js?config=TeX-AMS-MML_HTMLorMML%2CSafe.js&ver=4.1']
parentDir='\\'.join(baseUrl.split('/')[-3:]) #Parent directory from URL
for path in relativePaths: #For all files
req=requests.get(baseUrl+path) #forming url
filename=path.split("/")[-1].split("?")[0] #extracting filename out of url
directory=os.path.join(parentDir,"\\".join(path.split('/')[:-1])) #Extracting directories path for local path formation
if not os.path.exists(directory): #Creating local direcories if they do not exist
os.makedirs(directory)
with open(os.path.join(directory,filename),"wb+") as file: #Storing results into files
file.write(req.content)
Local Directory Structure Output:
Beyond iterating over a defined list of files, you could also look at a couple of other options that could take a more dynamic approach to fetch files from the CDN.
cdnjs is powered by a GitHub repository, so you could explore cloning it and extracting files (I'd recommend use sparse-checkout if you do this due to repo size) or you could look at using the GitHub API to navigate the repository an extract files: github.com/cdnjs/cdnjs/tree/master/ajax/libs/mathjax/2.7.5
We actually have an API available for cdnjs, which allows you to rather easily get all the files within a version of a library. Using that list, you could then perform a similar iterative solution to what Hamza suggested to get a copy of all the files locally: https://api.cdnjs.com/libraries/mathjax?fields=assets (annoyingly we've not yet implemented API navigation per version)
Hope that helps!
Matt, cdnjs maintainer.

Electron modify file store in .asar

I would like, from the Electron index.html file, to modify a config file present in the.asar of my application. In my case I need to change, if necessary, my application database config in order to work.
I understood that .asar is in readOnly and I wanted to know if there is a way to modify this config file from electron without changing its position in my application?
I see the extraResources option but I did not understand how its work.
It's also important that the config file stay in myapp/config folder.
Thanks for your help :)
What build tool do you use? If you are using electron builder, you can check out asarUnpack in configuration file here or extraFiles here
I was able to edit the read-only file by first changing the file permissions programmatically and then editing it.
fs.chmod(filename, 0666, (error) => {
console.log('Changed file permissions');
});
...
code to modify file
...
asar is in readonly
as you mentioned asar intended to be readonly package. For runtime-changing config, you should place it outside of asar and change values accordingly.
To manage settings you should use a node package that's specifically designed for this, like electron-settings or preferences.
As an alternative one may manually read an write config files that you place in the platform's native config directory.
Mutable application settings shouldn't be stored in the asar file. If it's required to replace a file in an asar archive for any other reason, use the the asar program to extract the entire archive to a temporary directory, replace the file(s) you want, then create a new asar file, replacing the original asar file.
To unpack .asar files -> asar extract electron.asar app
modify as per your needs
To pack .asar files -> asar pack . electron.asar

File location is not found in js file

I develop one js file and also call one js file from it, but I cannot find file. Error is "file not found". I debug in firebug. File url is not generate well. Code is:
require(['modules/PageDecorator'], function(PageDecorator){
//initializing visual ui
PageDecorator.init();
});
it it, modules is folder and PageDecorator is js file.
url is generated
localhost/js/models/PageDecorator.js
however I need it to be:
localhost/test/js/models/PageDecorator.js
test is my root folder.

Categories

Resources