Hello guys , i’ve installed libre office (for windows) ,
i’m working with node Js (nestJs framework) and i’m trying to convert the uploaded pdf to a word file ,
whenever i try upload the file im getting this error
Conversion error: [Error: ENOENT: no such file or directory, open ‘C:\Users\user\AppData\Local\Temp\libreofficeConvert_-12472-Bh0bjZYZoi4m\33e34cdc-a6c9-44e9-aac8-8986eeeadcf2.docx’] {
- errno: -4058,*
- code: ‘ENOENT’,*
- syscall: ‘open’,*
- path: ‘C:\Users\user\AppData\Local\Temp\libreofficeConvert_-12472-Bh0bjZYZoi4m\33e34cdc-a6c9-44e9-aac8-8986eeeadcf2.docx’*
}
here is the code
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { join } from 'path';
import { NestExpressApplication } from '@nestjs/platform-express';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe({ transform: true }));
app.useStaticAssets(join(process.cwd(), 'uploads'), {
prefix: '/uploads/',
});
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
import { Body, Controller, Post } from '@nestjs/common';
import { FormDataRequest } from 'nestjs-form-data';
import { UploadPdfDto } from 'src/dtos/upload-pdf.dto';
import { FileConvertorService } from './file-convertor.service';
@Controller('convert')
export class FileConvertorController {
constructor(private readonly fileConvertorService: FileConvertorService) {}
@Post('pdf-to-word')
@FormDataRequest()
async convertPdfToWord(@Body() { pdfFile }: UploadPdfDto) {
const result = await this.fileConvertorService.convertPdfToDocx(
pdfFile.buffer,
);
return result;
}
}
import { Injectable } from '@nestjs/common';
import { randomUUID } from 'crypto';
import * as libre from 'libreoffice-convert';
import * as fs from 'fs';
import * as path from 'path';
@Injectable()
export class FileConvertorService {
async convertPdfToDocx(pdfBuffer: Buffer) {
return new Promise((resolve, reject) => {
// Create filename and paths
const fileName = randomUUID();
const uploadDir = path.join(process.cwd(), 'uploads');
const filePath = path.join(uploadDir, fileName);
// Ensure uploads directory exists
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
libre.convertWithOptions(
pdfBuffer,
'docx',
undefined,
{
fileName: fileName,
tmpOptions: {
// dir: uploadDir, // Use our uploads directory for temp files
// prefix: 'convert-',
keep: true, // Keep the temporary files
},
},
(error, docxBuffer) => {
if (error) {
console.error('Conversion error:', error);
reject(error);
} else {
// Write the buffer to a file
fs.writeFileSync(filePath, docxBuffer);
// Return the URL that can be used to access the file
const fileUrl = `/uploads/${fileName}`;
resolve({ fileUrl });
}
},
);
});
}
}