Steps to Create Application and Installing Package
Step 1: Create a new folder for your project in your terminal or command prompt.
mkdir download-demo
Step 2: Navigate to the newly created folder.
cd download-demo
Step 3: Initialize npm to create a package.json file.
npm init -y
Step 4: Install the download package using npm.
npm install download
Project Structure:
Dependencies:
"dependencies": {
"download": "^8.0.0"
}
Example: In this example, we are using the download package to download a ZIP file from the specified URL and extract its contents to the ‘downloads/’ directory. The function downloadAndExtract handles the download process and provides user feedback via console messages.
// index.js
const download = require('download');
async function downloadAndExtract(url, destination) {
try {
console.log(`Starting download from ${url}...`);
await download(url, destination, { extract: true });
console.log('Download and extraction complete!');
} catch (error) {
console.error('An error occurred:', error);
}
}
const url =
'https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-zip-file.zip';
const destination = 'downloads/';
downloadAndExtract(url, destination);
Output:
npm download
npm download is a versatile utility that allows you to download and extract files from various sources directly within your Node.js applications. This package is especially useful for programmatically fetching files and handling them within your projects. Below, we will explore the installation process and basic usage of the download package.