Kamel Labiad
Kamel Labiad

Reputation: 547

How to know if file finished downloading?

I am developing an app for both mac and windows using electron that watches a folder for files that got downloaded there from another app, I want to check if file finishes downloading before moving it somewhere else, I don't know if should I check the file size periodically or is there another way to know if the file did finish downloading using javascript.

Upvotes: 1

Views: 1121

Answers (1)

Matthias Meiling
Matthias Meiling

Reputation: 46

You may use fs.watch and @ronomon/opened to solve your task. see: Check if a file is open in another process

I wrote a simple script, which worked fine on my windows 10 mashine. I downloaded a few files into the folder and it printed a correct notification, when download ended.

const fs = require ('fs');
const path = require ("path")
const opened = require('@ronomon/opened');

const base_path = "."
fs.watch (base_path, {encoding: "ascii", recursive: true}, (eventType, filename)=> {

    var file_path = path.join (base_path, filename);
    opened.files ([file_path], (error, hashtable) => {
        try {
            if (!hashtable[file_path]) {
                console.log ("file is closed and can be further processed", file_path)
            } else {
                console.log ("file is still opend by any other process...", file_path)
            }
        } catch (e) {
            console.error ("error: ", e);
        }
    })
});

Upvotes: 2

Related Questions