Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
electron-dl-manager
Advanced tools
A library for implementing file downloads in Electron with 'save as' dialog and id support.
A simple and easy to use file download manager for Electron applications.
Designed in response to the many issues around electron-dl
and provides
a more robust and reliable solution for downloading files in Electron.
Use cases:
Electron 26.0.0 or later is required.
// In main process
// Not a working example, just a demonstration of the API
import { FileDownloadManager } from 'electron-dl-manager';
const manager = new FileDownloadManager();
// Start a download
manager.download({
window: browserWindowInstance,
url: 'https://example.com/file.zip',
saveDialogOptions: {
title: 'Save File',
},
callbacks: {
onDownloadStarted: async ({ id, item, webContents }) => {
// Do something with the download id
},
onDownloadProgress: async (...) => {},
onDownloadCompleted: async (...) => {},
onDownloadCancelled: async (...) => {},
onDownloadInterrupted: async (...) => {},
onError: (err, data) => {},
}
});
manager.cancelDownload(id);
manager.pauseDownload(id);
manager.resumeDownload(id);
$ npm install electron-dl-manager
You'll want to use electron-dl-manager
in the main process of your
Electron application where you will be handling the file downloads.
In this example, we use IPC handlers / invokers to communicate between the main and renderer processes, but you can use any IPC strategy you want.
// MainIpcHandlers.ts
import { FileDownloadManager } from 'electron-dl-manager';
import { ipcMain } from 'electron';
const manager = new FileDownloadManager();
// Renderer would invoke this handler to start a download
ipcMain.handle('download-file', async (event, args) => {
const { url } = args;
let downloadId
const browserWindow = BrowserWindow.fromId(event.sender.id)
downloadId = manager.download({
window: browserWindow,
url,
callbacks: {
// item is an instance of Electron.DownloadItem
onDownloadStarted: async ({ id, item, resolvedFilename }) => {
// Send the download id back to the renderer along
// with some other data
browserWindow.webContents.invoke('download-started', {
id,
// The filename that the file will be saved as
filename: resolvedFilename,
// Get the file size to be downloaded in bytes
totalBytes: item.getTotalBytes(),
});
},
onDownloadProgress: async ({ id, item, percentCompleted }) => {
// Send the download progress back to the renderer
browserWindow.webContents.invoke('download-progress', {
id,
percentCompleted,
// Get the number of bytes received so far
bytesReceived: item.getReceivedBytes(),
});
},
onDownloadCompleted: async ({ id, item }) => {
// Send the download completion back to the renderer
browserWindow.webContents.invoke('download-completed', {
id,
// Get the path to the file that was downloaded
filePath: item.getSavePath(),
});
},
onError: (err, data) => {
// ... handle any errors
}
}
});
// Pause the download
manager.pauseDownload(downloadId);
});
FileDownloadManager
Manages file downloads in an Electron application.
constructor()
constructor(params: DownloadManagerConstructorParams)
interface DownloadManagerConstructorParams {
/**
* If defined, will log out internal debug messages
*/
debugLogger?: (message: string) => void
}
download()
Starts a file download. Returns the id
of the download.
download(params: DownloadParams): string
DownloadParams
interface DownloadParams {
/**
* The Electron.BrowserWindow instance
*/
window: BrowserWindow
/**
* The URL to download
*/
url: string
/**
* The callbacks to define to listen for download events
*/
callbacks: DownloadManagerCallbacks
/**
* Electron.DownloadURLOptions to pass to the downloadURL method
*
* @see https://www.electronjs.org/docs/latest/api/session#sesdownloadurlurl-options
*/
downloadURLOptions?: Electron.DownloadURLOptions
/**
* If defined, will show a save dialog when the user
* downloads a file.
*
* @see https://www.electronjs.org/docs/latest/api/dialog#dialogshowsavedialogbrowserwindow-options
*/
saveDialogOptions?: SaveDialogOptions
/**
* The filename to save the file as. If not defined, the filename
* from the server will be used.
*
* Only applies if saveDialogOptions is not defined.
*/
saveAsFilename?: string
/**
* The directory to save the file to. Must be an absolute path.
* @default The user's downloads directory
*/
directory?: string
/**
* If true, will overwrite the file if it already exists
* @default false
*/
overwrite?: boolean
/**
* If true, will show a badge on the dock icon when the download is in progress
* under MacOS and linux.
*
* On macOS, you need to ensure that your application has the permission to display notifications for this method to work.
*
* @default false
* @see https://www.electronjs.org/docs/latest/api/app#appsetbadgecountcount-linux-macos
*/
showBadge?: boolean
}
DownloadManagerCallbacks
interface DownloadManagerCallbacks {
onDownloadStarted: (data: DownloadManagerCallbackData) => void
onDownloadProgress: (data: DownloadManagerCallbackData) => void
onDownloadCompleted: (data: DownloadManagerCallbackData) => void
onDownloadCancelled: (data: DownloadManagerCallbackData) => void
onDownloadInterrupted: (data: DownloadManagerCallbackData) => void
// Note: data may be undefined or be incomplete
onError: (error: Error, data?: Partial<DownloadManagerCallbackData>) => void
}
interface DownloadManagerItem {
/**
* Generated id for the download
*/
id: string
/**
* The percentage of the download that has been completed
*/
percentCompleted: number
/**
* The name of the file that is being saved to the user's computer.
* Recommended over Item.getFilename() as it may be inaccurate when using the save as dialog.
*/
resolvedFilename: string
/**
* If true, the download was cancelled from the save as dialog
*/
cancelledFromSaveAsDialog?: boolean
}
interface DownloadManagerCallbackData extends DownloadManagerItem {
/**
* The Electron.DownloadItem. Use this to grab the filename, path, etc.
* @see https://www.electronjs.org/docs/latest/api/download-item
*/
item: DownloadItem
/**
* The Electron.WebContents
* @see https://www.electronjs.org/docs/latest/api/web-contents
*/
webContents: WebContents
/**
* The Electron.Event
* @see https://www.electronjs.org/docs/latest/api/event
*/
event: Event
}
cancelDownload()
Cancels a download.
cancelDownload(id: string): void
pauseDownload()
Pauses a download.
pauseDownload(id: string): void
resumeDownload()
Resumes a download.
resumeDownload(id: string): void
getActiveDownloadCount()
Returns the number of active downloads.
getActiveDownloadCount(): number
If you need to mock out ElectronDownloadManager
in your tests, you can use the ElectronDownloadManagerMock
class.
import { ElectronDownloadManagerMock } from 'electron-dl-manager'
# Acknowledgments
This code uses small portions from [`electron-dl`](https://github.com/sindresorhus/electron-dl) and is noted in the
code where it is used.
`electron-dl` is licensed under the MIT License and is maintained by Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com).
1.2.0 (2024-03-21)
disableThrottle()
where it was not working / throwingFAQs
A library for implementing file downloads in Electron with 'save as' dialog and id support.
We found that electron-dl-manager demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.