How to download a file with Node.js (without using third-party libraries)?
To download a file in Node.js without third-party libraries, use the http
or https
module based on the URL's protocol. Make a http.get()
or https.get()
call, and pipe the response to fs.createWriteStream
. Here's an example for an HTTPS URL:
Code breakdown and best practices
When downloading files using Node.js, itβs vital to consider the protocol being used. Whether the URL starts with http://
or https://
, pick the appropriate Node.js module.
Invoke http.get
or https.get
to initiate a GET request. This function provides a stream, which we can pipe directly to a writable stream created by fs.createWriteStream
. This method efficiently writes the incoming data to the file system.
Error handling and validation are boxes that cannot remain unchecked. Always confirm a HTTP 200 status code to make sure the download request was successful. Set up error listeners for both the request and file stream to catch network and file system issues.
Considerations for a robust execution
To make your download more robust, make sure to handle edge cases. Run through the following checklist:
- Network errors: May happen due to connectivity problems or request errors.
- File system permissions: Authorization issues on the output directory may prevent writing the file.
- Server Response: If the server's response isn't as expected (not receiving a 200 status code), abort the request.
- Partial Download: Ensure to delete the partially downloaded file if an error occurs to avoid corrupt files.
- Race Conditions: Be careful when other parts of your application are trying to access this file.
Downloading files from user input
For accepting input via the command line or making this operation part of a larger application's flow, wrap the download logic within a function and call it whenever needed.
Was this article helpful?