如何在不丢失其他警告的情况下,仅在Node.js中禁用Node.js警告?
ERROR (node:8) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.我知道Buffer()是不受欢迎的,我的代码中没有任何代码使用它,但是我的依赖项在使用它的链中很远,而且我不能立即修复它,所以我想沉默这些警告,因为它们被自动发送到Slack,这使得很难从我的应用程序中看到真正的错误。
我试过:
process.on('warning', (warning) => {
if (!warning.message.includes('Buffer() is deprecated')) {
console.error(warning);
}
});但这没有效果。我想这份通知是通过其他机制发出的。
我已经研究了修复调用new Buffer()的所有依赖项所需的内容,但是有很多,有些已经多年没有接受PRs,主要分支的测试失败等等,所以这不是一件容易的事情。此外,所有的公共关系都需要一段时间才能被接受、合并,并逐步上升。同时,我不希望每隔30秒发出一次警报,因为我做不到任何事情。
发布于 2020-11-20 16:27:39
这段猴子补丁代码将沉默特定的警告:
const origWarning = process.emitWarning;
process.emitWarning = function(...args) {
if (args[2] !== 'DEP0005') {
// pass any other warnings through normally
return origWarning.apply(process, args);
} else {
// do nothing, eat the warning
}
}显然,在运行生成警告的代码之前,必须运行此代码。
FYI,为了解决这个问题,我采取了以下步骤:
process.emitWarning(bufferWarning, 'DeprecationWarning', 'DEP0005');process.emitWarning()编写了一个猴子补丁,它寻找第三个参数为'DEP0005',这是特定于这个警告的参数。process.emitWarning() 这里的实现,以查看是否有任何标志或其他设置能够抑制特定的警告,以防出现支持的或更好的方法。没有找到这样的选择。DEP0005仅用于此特定警告,包括nodejs存储库中的搜索和警告医生中的搜索。https://stackoverflow.com/questions/64929200
复制相似问题