Node.js: console.err() 是同步的还是异步的?
Node.js: console.err() is syncronous or asyncronous?
我使用 AWS,我想使用 console.err()
将所有错误写入 stderr
。 stderr
被 AWS Cloud Watch 捕获并记录。我不想阻塞事件循环。
Node.js 实现中的 console.err()
是异步的吗?
出于教育目的,我将演示如何检查它,这样您下次就不需要再问了。
这是在最基本的情况下测试代码是否异步的方法:
const asyncOperation = async () => {
await new Promise( (res) => setTimeout(res, 1000))
console.log("Async finished")
}
console.log("Start")
asyncOperation()
console.log("End")
所以如果你 运行 它你会看到它先打印 "End" 然后再打印 "Async finished",因为 setTimeout 是异步的。
所以我会为你的案例添加新的片段,所以你知道。
const asyncOperation = () => {
console.error("Async Err?")
}
console.log("Start")
asyncOperation()
console.log("End")
运行 它,你会看到。你也可以在Node环境下试试,结果是一样的。
听@jonas-wilms 说的,他是对的,日志记录非常快
这取决于 OS 以及 stderr
的“进展”。
process.stdout
and process.stderr
differ from other Node.js streams in important ways:
They are used internally by console.log()
and console.error()
, respectively.
Writes may be synchronous depending on what the stream is connected to and whether the system is Windows or POSIX:
- Files: synchronous on Windows and POSIX
- TTYs (Terminals): asynchronous on Windows, synchronous on POSIX
- Pipes (and sockets): synchronous on Windows, asynchronous on POSIX
我使用 AWS,我想使用 console.err()
将所有错误写入 stderr
。 stderr
被 AWS Cloud Watch 捕获并记录。我不想阻塞事件循环。
Node.js 实现中的 console.err()
是异步的吗?
出于教育目的,我将演示如何检查它,这样您下次就不需要再问了。 这是在最基本的情况下测试代码是否异步的方法:
const asyncOperation = async () => {
await new Promise( (res) => setTimeout(res, 1000))
console.log("Async finished")
}
console.log("Start")
asyncOperation()
console.log("End")
所以如果你 运行 它你会看到它先打印 "End" 然后再打印 "Async finished",因为 setTimeout 是异步的。
所以我会为你的案例添加新的片段,所以你知道。
const asyncOperation = () => {
console.error("Async Err?")
}
console.log("Start")
asyncOperation()
console.log("End")
运行 它,你会看到。你也可以在Node环境下试试,结果是一样的。
听@jonas-wilms 说的,他是对的,日志记录非常快
这取决于 OS 以及 stderr
的“进展”。
process.stdout
andprocess.stderr
differ from other Node.js streams in important ways:
They are used internally by
console.log()
andconsole.error()
, respectively.Writes may be synchronous depending on what the stream is connected to and whether the system is Windows or POSIX:
- Files: synchronous on Windows and POSIX
- TTYs (Terminals): asynchronous on Windows, synchronous on POSIX
- Pipes (and sockets): synchronous on Windows, asynchronous on POSIX