How upload file in NestJS with websocket and FileInterceptor? - websocket

In docs https://docs.nestjs.com/techniques/file-upload we can use FileInterceptor, but how use it in EventsGateway?
For example:
#SubscribeMessage('user:setAvatar')
#UseInterceptors(FileInterceptor('userAvatar', {
storage: diskStorage({
destination: function(req, file, cb) {
console.log(file);
cb(null, 'uploads/');
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now());
}
})
}))
async setAvatar(client: any, #UploadedFile() file: any): Promise<void> {
console.log(file);
}

Related

Tesseract.js throw Error(data) cannot read properties of undefined (reading '_malloc') in tesseract file

I'm trying to use tesseract to convert image to text by upload image to my web app but got the error in the tesseract create worker.js like _malloc is undefined in throw Error(data).
I'm using tesseract version 2.1.5,
and I wrote the code from the video in 2019, I think maybe tesseract is changed from that time.
This is the error
This is code in app.js
const express = require("express");
const app = express();
const fs = require("fs");
const multer = require("multer");
const {createWorker} = require("tesseract.js");
const worker = createWorker({
logger: m => console.log(m)
});
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./uploads");
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({ storage: storage}).single("fname");
app.set("view engine", "ejs");
app.get('/', (req,res) => {
res.render('index');
});
app.post('/upload', (req,res) => {
upload(req, res, err => {
fs.readFile(`./uploads/${req.file.originalname}`, (err, data) => {
if(err) return console.log("Error", err);
worker
.recognize('./uploads/op.png')
.then(result => {
res.send(result.txt);
})
.finally(() => worker.terminate());
});
});
});

NextJs - Node - API resolved without sending a response for /api/xxx

I have a nextjs app with a backend api where I am sending an email out.
I have seen a couple of other posts with the same issue, have tried their resolutions and not sure what I am missing.
Any insight is appreciated.
The code in the API is below.
const nodemailer = require('nodemailer');
export default function (req, res) {
const mailData = {
from: 'xxxxx',
to: req.body.email,
subject: 'Message to Full On Consulting',
text: req.body.message,
html: '<div>'+req.body.message+'</div>'
}
sendMail(mailData)
.then((result) => {
console.log('Email sent...', result);
res.status(200).json({ status: 'SUCCESS' })
})
.catch((error) => console.log('Error ... ' + error.message));
}
async function sendMail(mailData) {
try {
let transport = nodemailer.createTransport({
host: "mail.xxxxxxxxxx.com",
port: 587,
secure: false,
auth: {
user: process.env.GMAIL_UID,
pass: process.env.GMAIL_PW
}
});
const result = await transport.sendMail(mailData)
return result;
} catch (error) {
console.log("CATCH ERROR: " + error)
return error;
}`enter code here`
}
I wrapped the sendmail call in a promise and that seems to have worked.
var promise = new Promise( (resolve, reject) => {
let result = transport.sendMail(mailData);
});
promise.then( result => {
console.log("PRomise Success ...");
}, function(error) {
console.log("Promise Failure...");
});

async await , nodejs readfile and then do other

I tried to read file through async/await and update the credentials , But i got response HI first and then hello in console.And Credentials also not updated in oauthClient2.
const getFile = async (req, res, next) => {
await fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return null;
console.log("hello")
console.log(JSON.parse(token));
oauth2Client.credentials = JSON.parse(token);
});
console.log("HI")
var service = google.drive({
version: 'v3',
encoding: null
});
console.log(oauth2Client);
await service.files.get({
auth: oauth2Client,
fileId: "1ZR8kkvb2JYVxcUjmlgfBJD2IYnisaiFn",
alt: 'media'
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
responder(res)(null,response);
});
}
Is there a way in which everything should run in a order?
Thank You.
The reason you are experiencing the error you see, is because the method you are running is asynchronous. You should instead use the alternative synchronous version:
let token;
try {
token = fs.readFileSync(TOKEN_PATH, 'utf8');
} catch (err) {
console.error(err)
}
if(!token){ return; }
oauth2Client.credentials = token;
const service = google.drive({
version: 'v3',
encoding: null
});
await service.files.get({
auth: oauth2Client,
fileId: "1ZR8kkvb2JYVxcUjmlgfBJD2IYnisaiFn",
alt: 'media'
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
responder(res)(null,response);
});
Ref: https://nodejs.dev/learn/reading-files-with-nodejs

puppeteer blank pdf generation

I'm using this simple code to generate a pdf document from http://example.com/
but I keep getting a blank pdf generated ...
Am I missing something ?
const puppeteer = require('puppeteer');
puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] }).then(function (browser) {
browser.newPage().then(function (page) {
page
.goto('http://example.com/', { waitUntil:['domcontentloaded', 'networkidle0','load'] })
.then(page.pdf({ path: 'result.pdf', format: 'letter' }))
.then(() => {
browser.close();
})
})
})
I used the no-sandbox option because of kernel issues.
I'm using CentOS 7
I had to wait for the promise in page.goto().then ...
const puppeteer = require('puppeteer');
puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] }).then(function (browser) {
browser.newPage().then(function (page) {
page
.goto('https://www.example.com', { waitUntil: ['domcontentloaded', 'networkidle0', 'load'] }).then(function (response) {
// page.emulateMedia('screen')
page.pdf({ path: 'result.pdf', format: 'letter' })
.then(function (res) {
browser.close();
}).catch(function (e) {
browser.close();
})
})
})
})

how to access to filename in my requst block in multer

I Need Access to file name in my request body because i want store in my db but i dont know handle that , this is my code :
var storage = multer.diskStorage({
destination: function (req, file, callback) {
var name = 'public/images/' + Math.floor((Math.random() * 10675712320) + 1);
fs.mkdir(name, (err)=> {
if (err) {
console.log(err);
} else {
** Im want pass name variable**
callback(null, name);
}
});
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
var upload = multer({storage: storage}).single('userPhoto');
app.post('/api/photo', function (req, res) {
***upload(req, res, function (data) {
I need access to file name here because i want store in my db***
console.log(data);
res.end("File is uploaded");
});
});
Im try this way but not working :
fs.mkdir(name, (err)=> {
if (err) {
console.log(err);
} else {
callback(name, name);
}
});
you can access to path from req.file.path like this :
var upload = multer({storage: storage}).single('userPhoto');
app.post('/api/photo', function (req, res) {
upload(req, res, function (data) {
console.log(req.file.path);
res.end("File is uploaded");
});
});

Resources