Search code examples
javascriptnode.jsnpmdesktop-applicationelectron

Download and store files inside electron app


I'm working on an app that on the first run will have to download files (images jpg/png) via API from the web and then store it locally so online connection won't be necessary anymore (user can run update when online and download newer data via api if there will be any updates available).

I'm aware that's very uncommon way how desktop app works but the main goal is to synchronize the desktop app data with web app.

So far, I've found a npm plugin request (link) to check whether user is connected to the internet or not.

I'm not sure is it possible to download and store files inside electron app (so it will be invisible outside the app) ? Can You recommend necessary plugins / tools to achieve such goal?

Any help will be appreciated.


Solution

  • Well, you can use the snippet from this answer and do it the node way.

    var http = require('http');
    var fs   = require('fs');
    var app  = require('remote').require('app')
    
    var file = fs.createWriteStream(app.getDataPath() + "externalFiles/file.jpg");
    var request = http.get("http://url-to-api/some-image.jpg", function(response) {
      response.pipe(file);
    });
    

    And you could use the App Data Path for storing the files. Of course, you would have to parse the name of the file from the URL, and then you are ready to go.

    You could also use web contents

    https://github.com/atom/electron/blob/master/docs/api/web-contents.md

    Then your app would be working as a browser, and offline support would have to be added by using local storage or some other technics.

    UPDATE:

    As today there are a couple of packages that can help with this like this one https://github.com/sindresorhus/electron-dl