Environment and Code
git clone [email protected]:nodejs/node.git
git checkout b07ff551db152ccb507e71160ce077e235206b16
Purpose
Taking the fs.readFile function as an example, let's see how Node.js implements it, thereby gaining insight into the underlying implementation details related to Node.js.
fs.readFileSync
The file location for fs.readFileSync js is at lib/fs.js:438
js-related implementations
/**
* Synchronously reads the entire contents of a file.
* @param {string | Buffer | URL | number} path
* @param {{
* encoding?: string | null;
* flag?: string;
* }} [options]
* @returns {string | Buffer}
*/
function readFileSync(path, options) {
// 读所以设置为 r flag
options = getOptions(options, { flag: 'r' });
if (options.encoding === 'utf8' || options.encoding === 'utf-8') {
if (!isInt32(path)) {
path = getValidatedPath(path);
}
return binding.readFileUtf8(path, stringToFlags(options.flag));
}
const isUserFd = isFd(path); // File descriptor ownership
const fd = isUserFd ? path : fs.openSync(path, options.flag, 0o666);
const stats = tryStatSync(fd, isUserFd);
const size = isFileType(stats, S_IFREG) ? stats[8] : 0;
let pos = 0;
let buffer; // Single buffer with file data
let buffers; // List for when size is unknown
if (size === 0) {
buffers = [];
} else {
buffer = tryCreateBuffer(size, fd, isUserFd);
}
let bytesRead;
if (size !== 0) {
do {
bytesRead = tryReadSync(fd, isUserFd, buffer, pos, size - pos);
pos += bytesRead;
} while (bytesRead !== 0 && pos < size);
} else {
do {
// The kernel lies about many files.
// Go ahead and try to read some bytes.
buffer = Buffer.allocUnsafe(8192);
bytesRead = tryReadSync(fd, isUserFd, buffer, 0, 8192);
if (bytesRead !== 0) {
ArrayPrototypePush(buffers, buffer.slice(0, bytesRead));
}
pos += bytesRead;
} while (bytesRead !== 0);
}
if (!isUserFd)
fs.closeSync(fd);
if (size === 0) {
// Data was collected into the buffers list.
buffer = Buffer.concat(buffers, pos);
} else if (pos < size) {
buffer = buffer.slice(0, pos);
}
if (options.encoding) buffer = buffer.toString(options.encoding);
return buffer;
}
As shown above, if options.encoding is set to utf8, the binding.readFileUtf8 function is called directly. This function is ultimately implemented in c++. The following section examines how internal modules are referenced, specifically where binding originates from. The relevant code from this file is excerpted below:
// lib/fs.js:66
const binding = internalBinding('fs');
The current issue is where internalBinding comes from, and why it can be called in a js file even though there is no function declaration for it. The same applies to functions like require. These aspects involve the c++ code that implements certain js functional interfaces within v8, as well as the module loading process during node startup. We will not discuss this in depth here, but a follow-up article will cover these topics.
What we need to focus on now is binding.readFileUtf8 and how this function is implemented.
Implementation related to binding.readFileUtf8
Regarding the implementation of binding.readFileUtf8, we suspect it is a function implemented in internal c++. Indeed, that is the case. How can we confirm this? We will not discuss that for now. We locate the relevant function at src/node_file.cc:2651. This file contains the code SetMethod(isolate, target, "readFileUtf8", ReadFileUtf8);. This confirms that the function name exposed to js is readFileUtf8, while the original function name is ReadFileUtf8. The detailed invocation timing and related information will be discussed in subsequent sections.
// src/node_file.cc:2651
// 该函数 c++ 实现,被 js 调用,v8 针对每一个回调都会有相关回调信息
static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
// Environment nodejs 封装环境信息的类, 后行文再讨论
Environment* env = Environment::GetCurrent(args);
// 当前 v8 的隔离容器
auto isolate = env->isolate();
CHECK_GE(args.Length(), 2);
CHECK(args[1]->IsInt32());
const int flags = args[1].As<Int32>()->Value();
// 后续实现实际是通过 libuv 实现的
// uv 文件描述符及 uv 文件状态
uv_file file;
uv_fs_t req;
// 判断是否为文件描述符
bool is_fd = args[0]->IsInt32();
// Check for file descriptor
if (is_fd) {
file = args[0].As<Int32>()->Value();
} else {
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
// 文件路径转换为 namespace 路径
ToNamespacedPath(env, &path);
// 文件权限检查
if (CheckOpenPermissions(env, path, flags).IsNothing()) return;
// 提供给程序监控用的相关信息
FS_SYNC_TRACE_BEGIN(open);
// 通过 uv_fs_open 打开文件
file = uv_fs_open(nullptr, &req, *path, flags, 0666, nullptr);
FS_SYNC_TRACE_END(open);
// 判断是否成功打开
if (req.result < 0) {
uv_fs_req_cleanup(&req);
// req will be cleaned up by scope leave.
return env->ThrowUVException(
static_cast<int>(req.result), "open", nullptr, path.out());
}
}
// 这里定义了该函数作用域离开时执行的相关操作
auto defer_close = OnScopeLeave([file, is_fd, &req]() {
if (!is_fd) {
FS_SYNC_TRACE_BEGIN(close);
CHECK_EQ(0, uv_fs_close(nullptr, &req, file, nullptr));
FS_SYNC_TRACE_END(close);
}
// 释放 req
uv_fs_req_cleanup(&req);
});
// 文件内容
std::string result{};
// 文件内容缓冲区
char buffer[8192];
// 初始化为 uv buffer
uv_buf_t buf = uv_buf_init(buffer, sizeof(buffer));
FS_SYNC_TRACE_BEGIN(read);
while (true) {
// 直接读直到读完
auto r = uv_fs_read(nullptr, &req, file, &buf, 1, -1, nullptr);
if (req.result < 0) {
FS_SYNC_TRACE_END(read);
// req will be cleaned up by scope leave.
return env->ThrowUVException(
static_cast<int>(req.result), "read", nullptr);
}
if (r <= 0) {
break;
}
result.append(buf.base, r);
}
FS_SYNC_TRACE_END(read);
// 转换为 v8 内部值供 js 访问
Local<Value> val;
if (!ToV8Value(env->context(), result, isolate).ToLocal(&val)) {
return;
}
// 设置 js 回调函数返回值
args.GetReturnValue().Set(val);
}
It is worth noting whether the uv_fs_read method is synchronous or asynchronous. In fact, this method can operate in both synchronous and asynchronous modes. A detailed explanation will be provided later. You can refer to the libuv code that node depends on for the specific implementation. Why, then, is fs.readFileSync, which calls this method, synchronous? This involves the distinction between synchronous and asynchronous scenarios. For the code that calls this method here, it must wait continuously until the result is returned after the call, which is synchronous and blocking. However, when this method is called asynchronously, it is asynchronous from the perspective of the event loop, and even more so for the node platform, which is built on top of the event loop, because the result is obtained in a subsequent event loop iteration after the file read completes. How would this change if we switched to an asynchronous approach? We can look at how the asynchronous implementation works in fs.read later.
tryReadSync
The remaining code for fs.readFileSync implements the data-reading logic in the js layer, but the core methods are still implemented in the c++ layer. fs.openSync calls Open at the underlying level, tryStatSync corresponds to FStat, fs.closeSync corresponds to Close, tryCreateBuffer corresponds to Uint8Array (v8), and tryReadSync corresponds to Read.
Let's take a look at the implementation of the Read function. The relevant code and comments are as follows:
// src/node_file.cc:2587
/*
* Wrapper for read(2).
*
* bytesRead = fs.read(fd, buffer, offset, length, position)
*
* 0 fd int32. file descriptor
* 1 buffer instance of Buffer
* 2 offset int64. offset to start reading into inside buffer
* 3 length int32. length to read
* 4 position int64. file position - -1 for current position
*/
// js 调用 c++ v8 回调信息
static void Read(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
const int argc = args.Length();
CHECK_GE(argc, 5);
CHECK(args[0]->IsInt32());
const int fd = args[0].As<Int32>()->Value();
CHECK(Buffer::HasInstance(args[1]));
// 转换为本地对象
Local<Object> buffer_obj = args[1].As<Object>();
char* buffer_data = Buffer::Data(buffer_obj);
size_t buffer_length = Buffer::Length(buffer_obj);
CHECK(IsSafeJsInt(args[2]));
const int64_t off_64 = args[2].As<Integer>()->Value();
CHECK_GE(off_64, 0);
CHECK_LT(static_cast<uint64_t>(off_64), buffer_length);
const size_t off = static_cast<size_t>(off_64);
CHECK(args[3]->IsInt32());
const size_t len = static_cast<size_t>(args[3].As<Int32>()->Value());
CHECK(Buffer::IsWithinBounds(off, len, buffer_length));
CHECK(IsSafeJsInt(args[4]) || args[4]->IsBigInt());
const int64_t pos = args[4]->IsNumber() ?
args[4].As<Integer>()->Value() :
args[4].As<BigInt>()->Int64Value();
char* buf = buffer_data + off;
uv_buf_t uvbuf = uv_buf_init(buf, len);
if (argc > 5) { // read(fd, buffer, offset, len, pos, req)
// 异步调用
FSReqBase* req_wrap_async = GetReqWrap(args, 5);
CHECK_NOT_NULL(req_wrap_async);
FS_ASYNC_TRACE_BEGIN0(UV_FS_READ, req_wrap_async)
AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger,
uv_fs_read, fd, &uvbuf, 1, pos);
} else { // read(fd, buffer, offset, len, pos)
// 同步调用
FSReqWrapSync req_wrap_sync("read");
FS_SYNC_TRACE_BEGIN(read);
const int bytesRead = SyncCallAndThrowOnError(
env, &req_wrap_sync, uv_fs_read, fd, &uvbuf, 1, pos);
FS_SYNC_TRACE_END(read, "bytesRead", bytesRead);
if (is_uv_error(bytesRead)) {
return;
}
args.GetReturnValue().Set(bytesRead);
}
}
From the code above, we can see that both synchronous and asynchronous calls are implemented through the Read function. The difference between synchronous and asynchronous calls lies in the use of FSReqBase and FSReqWrapSync, as well as AsyncCall and SyncCallAndThrowOnError. Since synchronous calls execute immediately, errors can be determined based on the return value. Under the hood, file operations are also completed via libuv. In contrast, because asynchronous calls do not execute immediately, they involve additional parameters, context information, and a callback. This callback is crucial. We will discuss the implementation of asynchronous calls later. For now, let's examine FSReqWrapSync and SyncCallAndThrowOnError for synchronous calls.
FSReqWrapSync
// src/node_file.h:458
class FSReqWrapSync {
public:
FSReqWrapSync(const char* syscall = nullptr,
const char* path = nullptr,
const char* dest = nullptr)
: syscall_p(syscall), path_p(path), dest_p(dest) {}
~FSReqWrapSync() { uv_fs_req_cleanup(&req); }
uv_fs_t req;
const char* syscall_p;
const char* path_p;
const char* dest_p;
FSReqWrapSync(const FSReqWrapSync&) = delete;
FSReqWrapSync& operator=(const FSReqWrapSync&) = delete;
// TODO(joyeecheung): move these out of FSReqWrapSync and into a special
// class for mkdirp
FSContinuationData* continuation_data() const {
return continuation_data_.get();
}
void set_continuation_data(std::unique_ptr<FSContinuationData> data) {
continuation_data_ = std::move(data);
}
private:
std::unique_ptr<FSContinuationData> continuation_data_;
};
As you can see, the implementation is relatively simple. The code FSReqWrapSync req_wrap_sync("read") mentioned in the Read function above is merely an instance that carries read as information for syscall_p. Let's take a look at SyncCallAndThrowOnError next.
SyncCallAndThrowOnError
The implementation of SyncCallAndThrowOnError actually calls SyncCallAndThrowIf:
// src/node_file-inl.h:389
// Similar to SyncCall but throws immediately if there is an error.
template <typename Func, typename... Args>
int SyncCallAndThrowOnError(Environment* env,
FSReqWrapSync* req_wrap,
Func fn,
Args... args) {
return SyncCallAndThrowIf(is_uv_error, env, req_wrap, fn, args...);
}
Take a look at SyncCallAndThrowIf:
// src/node_file-inl.h:366
// Similar to SyncCall but throws immediately if there is an error.
template <typename Predicate, typename Func, typename... Args>
int SyncCallAndThrowIf(Predicate should_throw,
Environment* env,
FSReqWrapSync* req_wrap,
Func fn,
Args... args) {
env->PrintSyncTrace();
int result = fn(nullptr, &(req_wrap->req), args..., nullptr);
if (should_throw(result)) {
env->ThrowUVException(result,
req_wrap->syscall_p,
nullptr,
req_wrap->path_p,
req_wrap->dest_p);
}
return result;
}
With this, by combining the details of the Read function call discussed above, we can see that fn(nullptr, &(req_wrap->req), args..., nullptr) ultimately resolves to the effective call uv_fs_read(nullptr, &(req_wrap->req), fd, &uvbuf, 1, pos, nullptr). You can refer to the function reference for uv_fs_read in libuv:
int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb)
By examining the corresponding function, we can easily see that the type of the req field in the FSReqWrapSync instance is uv_fs_t. However, we might wonder why loop can be nullptr. This is because in the implementation of the uv_fs_read function in libuv, if cb is null, it directly performs the system call using uv__fs_read. The relevant code is not shown here; readers can refer to it themselves. The reference path is as follows: deps/uv/src/unix/fs.c:2032 -> deps/uv/src/unix/fs.c:139 -> deps/uv/src/unix/fs.c:1695 -> deps/uv/src/unix/fs.c:516.
With this, we have essentially walked through the implementation of fs.readFileSync. Next, let's look at the implementation of fs.read, as well as the implementation of asynchronous calls.
fs.read
The location of the files related to fs.read in js is lib/fs.js:352. Below, comments are added to the relevant code:
// lib/fs.js:352
/**
* Asynchronously reads the entire contents of a file.
* @param {string | Buffer | URL | number} path
* @param {{
* encoding?: string | null;
* flag?: string;
* signal?: AbortSignal;
* } | string} [options]
* @param {(
* err?: Error,
* data?: string | Buffer
* ) => any} callback
* @returns {void}
*/
function readFile(path, options, callback) {
// 可能是三个或者两个参数
callback ||= options;
// 校验
validateFunction(callback, 'cb');
// 读所以设置为 r flag
options = getOptions(options, { flag: 'r' });
// js 实现的类 之后讨论
ReadFileContext ??= require('internal/fs/read/context');
// 初始化上下文
const context = new ReadFileContext(callback, options.encoding);
// 可能是文件描述符
context.isUserFd = isFd(path); // File descriptor ownership
if (options.signal) {
context.signal = options.signal;
}
// 如果是文件描述符的话, 同步函数执行完成之后会调用 readFileAfterOpen
if (context.isUserFd) {
process.nextTick(function tick(context) {
ReflectApply(readFileAfterOpen, { context }, [null, path]);
}, context);
return;
}
// 检查是否中断
if (checkAborted(options.signal, callback))
return;
const flagsNumber = stringToFlags(options.flag, 'options.flag');
// FSReqCallback 初始化
const req = new FSReqCallback();
req.context = context;
req.oncomplete = readFileAfterOpen;
// 调用内部 c++ 函数, 传递相关信息
binding.open(getValidatedPath(path), flagsNumber, 0o666, req);
}
ReadFileContext
Check the implementation related to ReadFileContext:
// lib/internal/fs/read/context.js:71
class ReadFileContext {
constructor(callback, encoding) {
this.fd = undefined;
this.isUserFd = undefined;
this.size = 0;
this.callback = callback;
this.buffers = null;
this.buffer = null;
this.pos = 0;
this.encoding = encoding;
this.err = null;
this.signal = undefined;
}
read() {
let buffer;
let offset;
let length;
// 检查是否中断
if (this.signal?.aborted) {
return this.close(
new AbortError(undefined, { cause: this.signal.reason }));
}
if (this.size === 0) {
// 第一次数据读取 buffer 初始化
// 位置 lib/internal/fs/utils.js:141
// const kReadFileUnknownBufferLength = 64 * 1024;
buffer = Buffer.allocUnsafeSlow(kReadFileUnknownBufferLength);
offset = 0;
length = kReadFileUnknownBufferLength;
this.buffer = buffer;
} else {
buffer = this.buffer;
offset = this.pos;
// 位置 lib/internal/fs/utils.js:142
// const kReadFileBufferLength = 512 * 1024;
length = MathMin(kReadFileBufferLength, this.size - this.pos);
}
// FSReqCallback 初始化
const req = new FSReqCallback();
// 绑定相关函数
req.oncomplete = readFileAfterRead;
req.context = this;
// 调用内部 c++ 函数, 传递相关信息
// 还是调用 Open 函数, 但是走的异步调用
read(this.fd, buffer, offset, length, -1, req);
}
close(err) {
if (this.isUserFd) {
process.nextTick(function tick(context) {
ReflectApply(readFileAfterClose, { context }, [null]);
}, this);
return;
}
// FSReqCallback 初始化
const req = new FSReqCallback();
req.oncomplete = readFileAfterClose;
req.context = this;
this.err = err;
// 调用内部 c++ 函数, 传递相关信息
// 还是调用 Close 函数, 但是走的异步调用
close(this.fd, req);
}
}
From the above, we can see that ReadFileContext is an encapsulation of reading and closing operations. After instantiation, you can perform related operations using read and close, all of which are asynchronous. Next, let's look at the readFileAfterOpen function.
readFileAfterOpen
The relevant implementation is located at lib/fs.js:298. The code is as follows:
// lib/fs.js:298
function readFileAfterOpen(err, fd) {
// 调用者为 ReadFileContext
const context = this.context;
// 错误检查
if (err) {
context.callback(err);
return;
}
context.fd = fd;
// 初始化 FSReqCallback 实例
const req = new FSReqCallback();
// 设置下一步事件
req.oncomplete = readFileAfterStat;
req.context = context;
// 调用 c++ 函数, 且为异步调用
binding.fstat(fd, false, req);
}
From the above, we can roughly see that the process starts by calling open. Once open completes, it calls req.oncomplete, which is readFileAfterOpen. If that succeeds, it then calls the fstat function. Note that this involves a new FSReqCallback instance. After fstat completes, it calls readFileAfterStat. If that succeeds, it is likely that the file can now be read, which is exactly what we expected. Let's look at the implementation of readFileAfterStat below:
// lib/fs.js:314
function readFileAfterStat(err, stats) {
const context = this.context;
if (err)
return context.close(err);
// TODO(BridgeAR): Check if allocating a smaller chunk is better performance
// wise, similar to the promise based version (less peak memory and chunked
// stringify operations vs multiple C++/JS boundary crossings).
const size = context.size = isFileType(stats, S_IFREG) ? stats[8] : 0;
if (size > kIoMaxLength) {
err = new ERR_FS_FILE_TOO_LARGE(size);
return context.close(err);
}
try {
if (size === 0) {
// TODO(BridgeAR): If an encoding is set, use the StringDecoder to concat
// the result and reuse the buffer instead of allocating a new one.
context.buffers = [];
} else {
context.buffer = Buffer.allocUnsafeSlow(size);
}
} catch (err) {
return context.close(err);
}
context.read();
}
Everything is basically as expected. On success, the file is read; on failure, the file is closed. Let's take a look at the implementation of FSReqCallback.
FSReqCallback
FSReqCallback is defined in a JS file originating from the built-in fs module, which corresponds to the c++ implementation. The code is as follows:
// lib/fs.js:66
const binding = internalBinding('fs');
// lib/fs.js:83
const {
FSReqCallback,
statValues,
} = binding;
Next, let's look at FSReqCallback in c++:
// src/node_file-inl.h:77
FSReqCallback::FSReqCallback(BindingData* binding_data,
v8::Local<v8::Object> req,
bool use_bigint)
: FSReqBase(binding_data,
req,
AsyncWrap::PROVIDER_FSREQCALLBACK,
use_bigint) {}
So what about FSReqBase? By tracing the related base classes, the path is FSReqCallback -> FSReqBase -> ReqWrap<uv_fs_t> -> AsyncWrap and ReqWrapBase. ReqWrapBase has no base class, so we continue tracing AsyncWrap -> BaseObject.
Now let's look at which methods of the FSReqCallback instance are primarily used in the read file related code mentioned above. At the same time, through the analysis above, we know that the read operation may call the open and fstat functions beforehand. We infer that the implementation of the open and fstat functions should be similar to the implementation of the Open and FStat functions in fs.readFileSync, especially regarding the use of FSReqCallback. Below, let's look at the implementation of the open function.
Open
The relevant code is as follows, located at src/node_file.cc:2581:
// src/node_file.cc:2581
static void Open(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
const int argc = args.Length();
CHECK_GE(argc, 3);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
CHECK(args[1]->IsInt32());
const int flags = args[1].As<Int32>()->Value();
CHECK(args[2]->IsInt32());
const int mode = args[2].As<Int32>()->Value();
if (argc > 3) { // open(path, flags, mode, req)
FSReqBase* req_wrap_async = GetReqWrap(args, 3);
CHECK_NOT_NULL(req_wrap_async);
if (AsyncCheckOpenPermissions(env, req_wrap_async, path, flags).IsNothing())
return;
req_wrap_async->set_is_plain_open(true);
FS_ASYNC_TRACE_BEGIN1(
UV_FS_OPEN, req_wrap_async, "path", TRACE_STR_COPY(*path))
AsyncCall(env, req_wrap_async, args, "open", UTF8, AfterInteger,
uv_fs_open, *path, flags, mode);
} else { // open(path, flags, mode)
if (CheckOpenPermissions(env, path, flags).IsNothing()) return;
FSReqWrapSync req_wrap_sync("open", *path);
FS_SYNC_TRACE_BEGIN(open);
int result = SyncCallAndThrowOnError(
env, &req_wrap_sync, uv_fs_open, *path, flags, mode);
FS_SYNC_TRACE_END(open);
if (is_uv_error(result)) return;
env->AddUnmanagedFd(result);
args.GetReturnValue().Set(result);
}
}
As you can see, the normal processing path still consists of two branches, corresponding to synchronous and asynchronous handling, respectively. The implementation is similar to the read function we analyzed earlier. Let's pay extra attention to the asynchronous implementation, because a successful open call checks the fstat status before proceeding to read. We can go directly back to the read function to examine the relevant asynchronous call section.
Asynchronous Processing in Read
// src/node_file.cc:2631
FSReqBase* req_wrap_async = GetReqWrap(args, 5);
CHECK_NOT_NULL(req_wrap_async);
FS_ASYNC_TRACE_BEGIN0(UV_FS_READ, req_wrap_async)
AsyncCall(env, req_wrap_async, args, "read", UTF8, AfterInteger,
uv_fs_read, fd, &uvbuf, 1, pos);
As shown above, we first obtain an instance of FSReqCallback. Since FSReqBase serves as its base class, we can directly upcast it to the base class here—much like turning a dog into an animal. Note that the FSReqCallback class stores relevant operation information. After that, we call the AsyncCall function, which is implemented as follows:
// src/node_file-inl.h:330
// Returns nullptr if the operation fails from the start.
template <typename Func, typename... Args>
FSReqBase* AsyncCall(Environment* env,
FSReqBase* req_wrap,
const v8::FunctionCallbackInfo<v8::Value>& args,
const char* syscall, enum encoding enc,
uv_fs_cb after, Func fn, Args... fn_args) {
return AsyncDestCall(env, req_wrap, args,
syscall, nullptr, 0, enc,
after, fn, fn_args...);
}
Continue tracing the AsyncDestCall function. The implementation is as follows:
// src/node_file-inl.h:307
// Returns nullptr if the operation fails from the start.
template <typename Func, typename... Args>
FSReqBase* AsyncDestCall(Environment* env, FSReqBase* req_wrap,
const v8::FunctionCallbackInfo<v8::Value>& args,
const char* syscall, const char* dest,
size_t len, enum encoding enc, uv_fs_cb after,
Func fn, Args... fn_args) {
CHECK_NOT_NULL(req_wrap);
req_wrap->Init(syscall, dest, len, enc);
int err = req_wrap->Dispatch(fn, fn_args..., after);
if (err < 0) {
uv_fs_t* uv_req = req_wrap->req();
uv_req->result = err;
uv_req->path = nullptr;
after(uv_req); // after may delete req_wrap if there is an error
req_wrap = nullptr;
} else {
req_wrap->SetReturnValue(args);
}
return req_wrap;
}
The main operation functions are req_wrap->Init and req_wrap->Dispatch. Based on their types, we can tell they come from the FSReqBase class. It is reasonable to guess that req_wrap->Init stores information related to the operation, and indeed, that is the case:
// src/node_file-inl.h:51
void FSReqBase::Init(const char* syscall,
const char* data,
size_t len,
enum encoding encoding) {
syscall_ = syscall;
encoding_ = encoding;
if (data != nullptr) {
CHECK(!has_data_);
buffer_.AllocateSufficientStorage(len + 1);
buffer_.SetLengthAndZeroTerminate(len);
memcpy(*buffer_, data, len);
has_data_ = true;
}
}
FSReqBase::FSReqBuffer&
FSReqBase::Init(const char* syscall, size_t len, enum encoding encoding) {
syscall_ = syscall;
encoding_ = encoding;
buffer_.AllocateSufficientStorage(len + 1);
has_data_ = false; // so that the data does not show up in error messages
return buffer_;
}
Let's take another look at the req_wrap->Dispatch function:
// src/req_wrap-inl.h:142
template <typename T>
template <typename LibuvFunction, typename... Args>
int ReqWrap<T>::Dispatch(LibuvFunction fn, Args... args) {
Dispatched();
// This expands as:
//
// int err = fn(env()->event_loop(), req(), arg1, arg2, Wrapper, arg3, ...)
// ^ ^ ^
// | | |
// \-- Omitted if `fn` has no | |
// first `uv_loop_t*` argument | |
// | |
// A function callback whose first argument | |
// matches the libuv request type is replaced ---/ |
// by the `Wrapper` method defined above |
// |
// Other (non-function) arguments are passed -----/
// through verbatim
int err = CallLibuvFunction<T, LibuvFunction>::Call(
fn,
env()->event_loop(),
req(),
MakeLibuvRequestCallback<T, Args>::For(this, args)...);
if (err >= 0) {
ClearWeak();
env()->IncreaseWaitingRequestCounter();
}
return err;
}
As can be seen, the final call is made to the CallLibuvFunction<T, LibuvFunction>::Call function. The implementation of this function is as follows. Based on semantic inference, it wraps libuv function calls and ultimately invokes the relevant libuv functions:
// src/req_wrap-inl.h:75
// Detect `int uv_foo(uv_loop_t* loop, uv_req_t* request, ...);`.
template <typename ReqT, typename... Args>
struct CallLibuvFunction<ReqT, int(*)(uv_loop_t*, ReqT*, Args...)> {
using T = int(*)(uv_loop_t*, ReqT*, Args...);
template <typename... PassedArgs>
static int Call(T fn, uv_loop_t* loop, ReqT* req, PassedArgs... args) {
return fn(loop, req, args...);
}
};
The final call is uv_fs_read(loop, req, fd, &uvbuf, 1, pos, AfterInteger). Since uv_fs_read is passed a callback function, it becomes an asynchronous call, meaning it goes through the event loop. At this point, we have reached the bottom of the stack, excluding the low-level system internals and libuv related implementations. However, we still have one question: what is the purpose of the callback AfterInteger? The implementation code is as follows:
// src/node_file.cc:802
void AfterInteger(uv_fs_t* req) {
FSReqBase* req_wrap = FSReqBase::from_req(req);
FSReqAfterScope after(req_wrap, req);
FS_ASYNC_TRACE_END1(
req->fs_type, req_wrap, "result", static_cast<int>(req->result))
int result = static_cast<int>(req->result);
if (result >= 0 && req_wrap->is_plain_open())
req_wrap->env()->AddUnmanagedFd(result);
if (after.Proceed())
req_wrap->Resolve(Integer::New(req_wrap->env()->isolate(), result));
}
Here, we can focus on the req_wrap->Resolve function. Since resolve is a core concept in promise, we can infer that this function should be related to promise. What exactly are these relationships? We will discuss this in detail later.
Summary
We conducted a bottom-up internal analysis of readFileSync and readFile. Both ultimately invoke the uv_fs_read function from libuv. The presence or absence of a cb (callback) determines whether a direct system call (synchronous invocation) is made or an asynchronous call is performed. However, we must not overlook the abstractions at each layer; these abstractions serve many purposes and reflect significant considerations in the architecture of the node platform. We will discuss the abstractions provided at each layer in the subsequent sections. Additionally, we have left several open questions, specifically regarding the loading and registration of built-in modules and how asynchrony is constructed. These topics will be addressed in later sections. We hope this analysis helps everyone better understand the node platform.
Comments (0)
No comments yet. Be the first to leave one!