Ներածություն:
Այս ձեռնարկում մենք կուսումնասիրենք, թե ինչպես կարելի է ստեղծել Node.js հավելված, որը թույլ է տալիս օգտվողներին վերբեռնել PDF ֆայլեր, մշակել այդ ֆայլերի բովանդակությունը և օգտակար տեղեկատվություն քաղել: Մենք կանդրադառնանք այնպիսի թեմաների, ինչպիսիք են ֆայլերի վերբեռնումը, ֆայլերը PDF ձևաչափի փոխակերպելը, PDF բովանդակության վերլուծությունը և բառերի առաջացման հաշվումը: Այս ձեռնարկի ավարտին դուք լավ կհասկանաք, թե ինչպես աշխատել PDF ֆայլերի հետ Node.js-ում:
Նախադրյալներ.
Այս ձեռնարկին հետևելու համար դուք պետք է հիմնական պատկերացում ունենաք JavaScript-ի, Node.js-ի և վեբ զարգացման հայեցակարգերի մասին: Բացի այդ, համոզվեք, որ Node.js-ը տեղադրված է ձեր մեքենայի վրա:
Քայլ 1. Նախագծի կարգավորում
Նախքան կոդի մեջ մտնելը, եկեք ստեղծենք նախագծի կառուցվածքը և տեղադրենք անհրաժեշտ կախվածությունները: Ահա քայլերը.
1. Ստեղծեք նոր գրացուցակ ձեր նախագծի համար:
2. Բացեք տերմինալ և անցեք ծրագրի գրացուցակ:
3. Նախաձեռնեք նոր Node.js նախագիծը՝ գործարկելով «npm init -y» հրամանը:
4. Տեղադրեք անհրաժեշտ կախվածությունները՝ գործարկելով հետևյալ հրամանը.
npm install express pdf-parse fs multer path mammoth html-pdf
Քայլ 2. Էքսպրես հավելվածի ստեղծում
Սկսենք ստեղծելով Express հավելվածը և կարգավորելով անհրաժեշտ միջնակարգ ծրագիրը: Հետևեք այս քայլերին.
1. Ստեղծեք նոր ֆայլ, որը կոչվում է «app.js»:
2. Բացեք «app.js» ֆայլը և ներմուծեք անհրաժեշտ մոդուլները.
const express = require('express'); const PDFParser = require('pdf-parse'); const fs = require('fs'); const app = express(); const uploadDirectory = './uploads'; const multer = require('multer'); const path = require('path'); const mammoth = require('mammoth'); const pdf = require('html-pdf');
3. Ստեղծեք անհրաժեշտ միջին ծրագիրը.
app.use(express.json()); app.use(express.urlencoded({ extended: true }));
4. Սահմանեք մուլտերի պահեստավորման կոնֆիգուրացիան.
const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'uploads/'); }, filename: (req, file, cb) => { cb(null, file.originalname); } }); const upload = multer({ storage });
5. Ավելացրեք երթուղին՝ ֆայլերի վերբեռնումները կարգավորելու համար.
app.post('/upload', upload.single('file'), async (req, res) => { // File upload logic goes here });
6. Գործարկեք սերվերը.
app.listen(3000, () => { console.log('Server is running on port 3000'); });
Քայլ 3. Ֆայլերի վերբեռնումների կառավարում
Այս քայլում մենք կկարգավորենք ֆայլերի վերբեռնումները և կմշակենք վերբեռնված ֆայլը: Ահա երթուղու մշակողի ներսում ավելացնելու կոդը.
app.post('/upload', upload.single('file'), async (req, res) => { try { // Check if a file was uploaded if (!req.file) { return res.status(400).json({ error: 'No file uploaded' }); } // Retrieve the uploaded file from the request body const uploadedFile = req.file; // Write the file to the upload directory const fileName = `${uploadedFile.originalname}`; const filePath = `${uploadDirectory}/${fileName}`; const fileData = fs.readFileSync(filePath, 'utf8'); await processFileData(fileData); // Determine the file type const fileExtension = uploadedFile.mimetype ?uploadedFile.mimetype : null; // Check if the file is already in PDF format if (fileExtension === 'application/pdf') { // Process the PDF directly await processPDF(filePath, res); } else { // Convert the file to PDF const convertedFilePath = await convertToPDF(filePath); // Process the converted PDF await processPDF(convertedFilePath, res); } } catch (error) { console.error('An error occurred while processing the file:', error); res.status(500).json({ error: 'Failed to process the file' }); } });
Քայլ 4. PDF-ի մշակում և բառերի առաջացման հաշվում
Այս քայլում մենք կսահմանենք PDF ֆայլը մշակելու և բառերի դեպքերը հաշվելու գործառույթները: Ահա ավելացման կոդը.
// Function to process the file data (perform your file processing logic here) function processFileData(fileData) { fs.writeFile('output.txt', fileData, (err) => { if (err) { console.error('Error writing file:', err); } else { console.log('File written successfully'); } }); } // Function to process the PDF and count word occurrences async function processPDF(pdfFilePath, res) { try { // Parse the PDF content const pdfBuffer = fs.readFileSync(pdfFilePath); const data = await PDFParser(pdfBuffer); const pdfText = data.text; // Define the words to search and their initial count const technologies = ['Node.js', 'React.js', 'Angular', 'Vue.js', 'JavaScript', 'TypeScript', 'HTML', 'CSS', 'Sass', 'Bootstrap', 'jQuery', 'Python', 'Java', 'Ruby', 'Go', 'PHP', 'Swift', 'Kotlin', 'Rust', 'SQL', 'MongoDB', 'Firebase', 'AWS', 'Azure', 'Docker', 'Kubernetes', 'Git', 'GitHub', 'Jenkins', 'CI/CD', 'REST API', 'GraphQL', 'OAuth', 'JSON', 'XML', 'Microservices', 'Artificial Intelligence', 'Machine Learning', 'Data Science', 'Big Data', 'Blockchain']; let wordCounts = {}; // Count the occurrences of each search word technologies.forEach((word) => { const regex = new RegExp(word, 'gi'); const count = (pdfText.match(regex) || []).length; wordCounts[word] = count; }); // Return the word counts as the response wordCounts = Object.fromEntries(Object.entries(wordCounts).filter(([key, value]) => value !== 0)); res.json({ wordCounts }); } catch (error) { console.error('An error occurred while processing the PDF:', error); res.status(500).json({ error: 'Failed to process the PDF' }); } finally { // Clean up - delete the uploaded file and PDF file if needed } } // Helper function to convert files to PDF using external converter async function convertToPDF(filePath) { return new Promise((resolve, reject) => { const convertedFilePath = path.join('converted/', `${path.parse(filePath).name}.pdf`); mammoth.extractRawText({ path: filePath }) .then((result) => { const html = `<html><body>${result.value}</body></html>`; pdf.create(html).toFile(convertedFilePath, (error) => { if (error) { reject(error); } else { resolve(convertedFilePath); } }); }) .catch((error) => { reject(error); }); });