A Node.js application designed to generate a QR code from a user-provided URL and save both the QR code image and the URL itself to the local file system. The project leverages npm for package management, user interaction via the terminal, QR code generation, and file system operations. This project is a Node.js application designed to generate a QR code from a user-provided URL and save both the QR code image and the URL itself to the local file system. The project leverages several key technologies and npm packages to accomplish these tasks efficiently.
-
Initialize npm: Start by initializing npm in the project directory to create a
package.jsonfile. This file manages the project's dependencies.npm init
-
Install Dependencies: Install the required packages,
inquirerandqr-image.npm install inquirer qr-image
-
Import Modules: Import the necessary modules:
inquirerfor handling user input.qr-imagefor generating QR codes.- Node.js native
fs(file system) module for file operations.
import inquirer from 'inquirer'; import qr from 'qr-image'; import * as fs from 'node:fs';
- User Input: The application uses
inquirerto prompt the user to enter a URL. The prompt is configured to ask for a URL input with a default value ofhttps://www.google.com/.inquirer.prompt([ { type: 'input', name: 'userInputURL', message: 'Enter your URL: ', default: 'https://www.google.com/' } ]) .then((answers) => { const userInputURL = answers.userInputURL; // Generate QR code var qr_image = qr.image(userInputURL); // Generates QR code as a PNG image qr_image.pipe(fs.createWriteStream('qrImage.png')); // Save QR code image to file // Save URL to text file fs.writeFile('userInput.txt', `User Inputs are: ${userInputURL}`, (err) => { if (err) throw err; console.log('The URL has been saved!'); }); }) .catch((error) => { if (error.isTtyError) { console.log('Prompt failed to render in the current environment'); } else { console.log('An unexpected error occurred'); } });
- User Input Handling: Utilizes
inquirerto interactively receive URL input from the user. - QR Code Generation: Uses
qr-imageto create a QR code from the input URL. The QR code is generated as a PNG image and saved to the file system. - File Operations: Employs the native
fsmodule to write the user-provided URL to a text file nameduserInput.txt.
The script includes basic error handling to manage potential issues during user prompt interactions and file operations, ensuring robustness and user-friendly feedback.
This project demonstrates effective use of npm for package management, user interaction via the terminal, QR code generation, and file system operations, making it a practical example of a simple yet powerful Node.js application.