Node.js - process.exit 并将整个 console.log 消息附加到文本文件中

Node.js - process.exit AND append the entire console.log messages in a text file

我是 Puppeteer 的菜鸟。 我正在使用登录网站的脚本。如果用户名或密码错误,我想将控制台消息记录在文件中并以错误号退出。这个数字很重要,因为它将在 Excel VBA 中使用。 我使用文件批处理 (Windows) 到 运行 node.js 脚本,我在脚本开头使用一个函数来附加控制台消息。

我运行一个批处理文件到运行脚本:

node C:\*my-path*\node-script.js
exit /b %errorlevel%

我可以在控制台中看到该消息,但在日志文件中没有完整的错误消息,因为 process.exit(1) 关闭了它之前的过程。

这是附加 console.log 消息的函数:

fs.unlinkSync("./tmp/node-js.log");
console.log = function(msg) {
    fs.appendFile("./tmp/node-js.log", msg+'\r\n', 'ascii', function(err) {
        if(err) {
            return trueLog(err);
        }
    });
    trueLog(msg);

然后,这是登录代码:

await page.goto('https://google-wrong.com/', {  //a wrong url to test
                waitUntil: 'networkidle2',
                timeout: 10000
}).catch(error => {
    throw (console.log('\r\n'+ 'JAVASCRIPT * Wrong Url ! * ' + error)), process.exit(1) });

因此,如果我使用 browser.close() 而不是 process.exit(1),我可以附加整个消息,但不能以错误代码退出;这是我的 console.log:

> Open browser in memory... Done!
> Connect to google-wrong.com... Error!
> JAVASCRIPT * Wrong Url ! * Error: net::ERR_NAME_NOT_RESOLVED at https://google-wrong.com/

在 Dos 提示符下我看到:

> exit /b 0

如果我使用 process.exit(1),我可以看到 "exit with error" 号码:

exit /b 1

...但我无法记录整个消息:

> Open browser in memory... Done!
> Connect to google-wrong.com... Error

有什么想法吗? 提前致谢,抱歉我的英语不好,我希望我说清楚了。

我认为您应该在 console.log 函数中使用 fs.appendFileSync,并且不需要在 catch 处理程序中使用 throw 关键字