回调的示例
回调的形式将完成回调函数作为其最后一个参数并且异步地调用该操作。
传给完成回调的参数取决于方法,但是第一个参数始终预留用于异常。
如果操作成功地完成,则第一个参数为 null
或 undefined
。
import { unlink } from 'fs';
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
const { unlink } = require('fs');
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
当达到最佳性能时(无论是在执行时间还是在内存分配方面),fs
模块基于回调的 API 版本都比使用 promise API 更好。
The callback form takes a completion callback function as its last
argument and invokes the operation asynchronously. The arguments passed to
the completion callback depend on the method, but the first argument is always
reserved for an exception. If the operation is completed successfully, then
the first argument is null
or undefined
.
import { unlink } from 'fs';
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
const { unlink } = require('fs');
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
The callback-based versions of the fs
module APIs are preferable over
the use of the promise APIs when maximal performance (both in terms of
execution time and memory allocation are required).