I'm trying to send messages from Node.js to whatsapp using the whatsapp-web.js library, I'm following a tutorial on YT from @LeiferMendez(excellent Youtuber) but when I wanted to create the qr-code I received the following error:
This is my app.js
import { writeFile, existsSync } from 'fs';
import { readFile } from 'fs/promises';
import ora from 'ora';
import chalk from 'chalk';
import { Client } from 'whatsapp-web.js';
//import SESSION_FILE_PATH from './session.json'
import pkg from 'qrcode-terminal';
const { generate } = pkg;
//const qrcode = require('qrcode-terminal');
//const chalk = require('chalk');
const SESSION_FILE_PATH = JSON.parse(
await readFile(
new URL('./session.json',
import.meta.url)
)
);
//const SESSION_FILE_PATH = './session.json';
let client;
let sessionData;
const withSession = () => {
const spinner = ora(`Cargando ${chalk.yellow('Verified session with Whatsapp...')}`);
sessionData = SESSION_FILE_PATH;
spinner.start();
client = new Client({
session: sessionData
})
client.on('ready', () => {
console.log('Client is ready!');
spinner.stop();
})
client.on('auth_failure', () => {
spinner.stop();
})
client.initialize();
}
//Crear qr para enlazar el punto origen
const withOutSession = () => {
console.log('not session saved');
client = new Client();
client.on('qr', qr => {
console.log(qr);
generate(qr, { small: true });
});
client.on('authenticated', (session) => {
//Guardamos credenciales de session para usar luego
sessionData = session;
writeFile(SESSION_FILE_PATH, JSON.stringify(session), (err) => {
if (err) {
console.log(err);
}
})
})
client.initialize();
}
(existsSync(SESSION_FILE_PATH)) ? withSession(): withOutSession();
I attach my package.json in a repo:
https://github.com/IzliaB/packagejson-whatsappEnd/blob/main/package.json
As I was reading this error happens because after a certain number of characters, the QR code is no longer displayed on the screen. If the exercise searches if there is already a record or a session created, which is stored in a session.json then the app searches the file if not, the qr is generated, but I don't know if there is a limit to do it or something like that, what do you think? Do you know why this happens?
The problem is in the line
const { generate } = pkg;
This code works fine:
The result:
I have no idea why it
const { generate } = pkg
creates the error