There is no async API for file operations so node.js uses a thread pool for that. You can see it in the code of libuv.
The pool can run 4 threads:
static uv_thread_t default_threads[4];
Blocking FS tasks are posted with uv__work_submit. For example, here's how read is implemented:
int uv_fs_read(uv_loop_t* loop, uv_fs_t* req,
uv_file file,
void* buf,
size_t len,
int64_t off,
uv_fs_cb cb) {
INIT(READ);
req->file = file;
req->buf = buf;
req->len = len;
req->off = off;
POST;
}
...
#define POST
do {
if ((cb) != NULL) {
uv__work_submit((loop), &(req)->work_req, uv__fs_work, uv__fs_done);
return 0;
}
else {
uv__fs_work(&(req)->work_req);
uv__fs_done(&(req)->work_req, 0);
return (req)->result;
}
}
while (0)
If you want to implement your own threads, you can check this great introduction.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…