关于Node.js fs模块stat函数体位置及回调参数来源的技术咨询
fs.stat Callback Arguments and Implementation Great question—you’re right on the money with your initial guess! Let’s unpack this clearly:
Where do err and stats come from?
Your callback function isn’t just sitting around waiting—the internal implementation of fs.stat is what calls it and passes those arguments when the file system operation finishes. Here’s the breakdown:
- When you call
fs.stat(filepath, yourCallback), Node.js kicks off an asynchronous request to your operating system to retrieve metadata about the file/directory atfilepath. - If something goes wrong during this operation (like the file doesn’t exist, you don’t have permission to access it, or there’s a disk error), Node.js creates a
NodeJS.ErrnoExceptionobject containing details about the failure, and passes this as the firsterrargument to your callback. - If the operation succeeds, Node.js takes the metadata returned by the OS (like file size, creation time, whether it’s a directory) and wraps it into a
Statsobject, then passes this as the secondstatsargument to your callback.
In your code example, if filepath points to a non-existent file, the internal fs.stat logic will trigger your callback with a non-null err, which is why your 404 handling code runs.
Where is the stat function body located?
Node.js core modules (including fs) are a mix of JavaScript and C++ code:
- The JavaScript wrapper for
fs.statlives in the Node.js source code atlib/fs.js. This layer handles argument validation, sets up the asynchronous operation, and manages the callback triggering. - The actual heavy lifting (talking to the OS file system) is done in C++ code, located in the
src/fs_*.ccfiles in the Node.js repository. This is where the OS-specific file system calls happen.
You don’t need to dive into the C++ code for everyday Node.js development, but if you’re curious, you can explore the Node.js open-source repository to see the full implementation.
内容的提问来源于stack exchange,提问作者Jason Paul

