如何获取Node.js进程占比?多页PDF转图片进度追踪方法咨询
Great question! Let's break this down into two parts: tracking PDF conversion progress when using node-pdf-image for large documents, and monitoring Node.js process resource usage if that's a fallback you're considering.
The node-pdf-image library doesn't natively expose progress callbacks for batch conversions, but you can implement this manually with a few extra steps:
- First fetch the total number of pages in your PDF
- Convert pages one by one (instead of using the bulk
convert()method) - Calculate and report progress as each page completes
Step 1: Get the total page count
Use a lightweight library like pdf-parse to extract the page count without converting the entire document:
const pdfParse = require('pdf-parse'); const fs = require('fs'); async function getTotalPages(pdfPath) { const dataBuffer = fs.readFileSync(pdfPath); const pdfData = await pdfParse(dataBuffer); return pdfData.numpages; }
Step 2: Convert pages individually and track progress
Use the library's convertPage() method in a loop, updating progress after each page finishes processing:
const PDFImage = require('pdf-image').PDFImage; async function convertPdfWithProgress(pdfPath) { const totalPages = await getTotalPages(pdfPath); const pdfImage = new PDFImage(pdfPath); for (let pageNum = 1; pageNum <= totalPages; pageNum++) { await pdfImage.convertPage(pageNum); const progressPercent = ((pageNum / totalPages) * 100).toFixed(2); console.log(`Conversion progress: ${progressPercent}% (Page ${pageNum}/${totalPages})`); } console.log('Conversion complete!'); } // Run the conversion with progress tracking convertPdfWithProgress('./large-document.pdf');
This approach gives you precise control over tracking both the current page and completion percentage—ideal for PDFs with 50+ pages.
If you also want to track CPU/memory usage during the conversion, libraries like pidusage are perfect for the job. It lets you fetch real-time metrics for any process ID, including your Node.js app's own PID.
Example with pidusage
const pidusage = require('pidusage'); const process = require('process'); // Function to log current process stats async function logProcessStats() { const stats = await pidusage(process.pid); console.log(`CPU Usage: ${stats.cpu.toFixed(2)}% | Memory Usage: ${(stats.memory / 1024 / 1024).toFixed(2)} MB`); } // Log stats every 2 seconds during conversion const statsInterval = setInterval(logProcessStats, 2000); // Wrap conversion with monitoring cleanup async function convertAndMonitor(pdfPath) { try { await convertPdfWithProgress(pdfPath); } finally { clearInterval(statsInterval); console.log('Process monitoring stopped'); } } // Start monitored conversion convertAndMonitor('./large-document.pdf');
This will give you ongoing insights into how much system resources the conversion is consuming, which can help with optimization or troubleshooting large PDF jobs.
内容的提问来源于stack exchange,提问作者Vive

