同步示例
【Synchronous example】
同步 API 会阻塞 Node.js 的事件循环和后续的 JavaScript 执行,直到操作完成。异常会立即抛出,可以使用 try…catch 进行处理,或者允许异常向上冒泡。
【The synchronous APIs block the Node.js event loop and further JavaScript
execution until the operation is complete. Exceptions are thrown immediately
and can be handled using try…catch, or can be allowed to bubble up.】
import { unlinkSync } from 'node:fs';
try {
unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (err) {
// handle the error
}const { unlinkSync } = require('node:fs');
try {
unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (err) {
// handle the error
}