Если вы используете wwebjs-1.26.3@alpha.3 с LocalAuth и столкнулись с проблемой, при которой приложение аварийно завершает работу, когда пользователь вручную выходит из своего телефона, это связано с ошибкой в метод выхода из файла LocalAuth.js.
Ошибка возникает из-за того, что метод fs.promises.rm() не обрабатывает повторные попытки должным образом, что приводит к сбою приложения, если сеанс Не удалось удалить каталог.
Решение:
Обновите файл LocalAuth.js, включив в него механизм повторной попытки удаления каталога сеанса. Вот исправление:
Старый код (в LocalAuth.js):
Код: Выделить всё
'use strict';
const path = require('path');
const fs = require('fs');
const BaseAuthStrategy = require('./BaseAuthStrategy');
class LocalAuth extends BaseAuthStrategy {
constructor({ clientId, dataPath }={}) {
super();
const idRegex = /^[-_\w]+$/i;
if(clientId && !idRegex.test(clientId)) {
throw new Error('Invalid clientId. Only alphanumeric characters, underscores and hyphens are allowed.');
}
this.dataPath = path.resolve(dataPath || './.wwebjs_auth/');
this.clientId = clientId;
}
async logout() {
if (this.userDataDir) {
await fs.promises.rm(this.userDataDir, { recursive: true, force: true })
.catch((e) => {
throw new Error(e);
});
}
}
}
module.exports = LocalAuth;
Код: Выделить всё
'use strict';
const path = require('path');
const fs = require('fs-extra');
const BaseAuthStrategy = require('./BaseAuthStrategy');
// Helper function
async function deleteDirectoryWithRetries(path, retries = 5, delayMs = 500) {
for (let attempt = 1; attempt setTimeout(res, delayMs));
} else {
throw error;
}
}
}
}
////
/**
* Local directory-based authentication
* @param {object} options - options
* @param {string} options.clientId - Client id to distinguish instances if you are using multiple, otherwise keep null if you are using only one instance
* @param {string} options.dataPath - Change the default path for saving session files, default is: "./.wwebjs_auth/"
*/
class LocalAuth extends BaseAuthStrategy {
constructor({ clientId, dataPath } = {}) {
super();
const idRegex = /^[-_\w]+$/i;
if (clientId && !idRegex.test(clientId)) {
throw new Error('Invalid clientId. Only alphanumeric characters, underscores and hyphens are allowed.');
}
this.dataPath = path.resolve(dataPath || './.wwebjs_auth/');
this.clientId = clientId;
}
async beforeBrowserInitialized() {
const puppeteerOpts = this.client.options.puppeteer;
const sessionDirName = this.clientId ? `session-${this.clientId}` : 'session';
const dirPath = path.join(this.dataPath, sessionDirName);
if (puppeteerOpts.userDataDir && puppeteerOpts.userDataDir !== dirPath) {
throw new Error('LocalAuth is not compatible with a user-supplied userDataDir.');
}
fs.mkdirSync(dirPath, { recursive: true });
this.client.options.puppeteer = {
...puppeteerOpts,
userDataDir: dirPath
};
this.userDataDir = dirPath;
}
async logout() {
if (this.userDataDir) {
try {
// 1) First, gracefully shut down the client/browser
if (this.client) {
await this.client.destroy();
}
// 2) Then, remove the session files from disk
await deleteDirectoryWithRetries(this.userDataDir);
console.log('Logout completed successfully. Session directory removed.');
} catch (e) {
console.error(`Logout failed: ${e.message}`);
// throw new Error(`Logout failed: ${e.message}`); // or handle it as needed
}
}
}
}
module.exports = LocalAuth;
Чтобы применить это исправление, используйте исправленную библиотеку с GitHub, установив ее напрямую:
Код: Выделить всё
npm install github:Max77788/whatsapp-web.js#fix/localauth-logout
Почему это работает:
Новая реализация включает опцию maxRetries для fs.promises.rm(), которая гарантирует повторную попытку удаления каталога сеанса в случае временных проблем с файловой системой. Это предотвращает сбой приложения во время выхода из системы вручную.
Если у вас по-прежнему возникают проблемы, оставьте комментарий ниже!
Подробнее здесь: https://stackoverflow.com/questions/793 ... gs-out-man