Skip to main content

nodejs/stdlib/
fs_promises.rs

1//! Node `fs/promises` (also `require('fs').promises`) — Promise-returning file
2//! operations.
3//!
4//! Every method delegates to the SAME synchronous I/O the `*Sync` `fs` module
5//! performs (`readFile`→`readFileSync`, `chmod`→`chmodSync`, …), then wraps the
6//! outcome in a settled Promise: fulfilled with the value on success, rejected
7//! with an `Error` object on failure. Delegating to `fs::call` keeps the encoding
8//! handling, `Stats`/`Dirent`/`Dir` shapes, and error strings identical to the
9//! rest of `fs`.
10//!
11//! `open` returns a `FileHandle`: a port of node's class over the same
12//! synchronous descriptor calls (`fs_filehandle.js`), which `readFile`,
13//! `writeFile` and `appendFile` also route through when handed one.
14//!
15//! The work is performed synchronously (node-js has no thread-pooled `fs` at this
16//! layer), and the Promise settles in the loop's poll phase, as an I/O
17//! completion — ordered with the callback forms' completions, as in node.
18
19use crate::host::with_host;
20use fusevm::Value;
21
22pub const METHODS: &[&str] = &[
23    "readFile",
24    "writeFile",
25    "appendFile",
26    "readdir",
27    "mkdir",
28    "rmdir",
29    "rm",
30    "unlink",
31    "stat",
32    "lstat",
33    "statfs",
34    "access",
35    "rename",
36    "copyFile",
37    "cp",
38    "chmod",
39    "chown",
40    "lchown",
41    "link",
42    "symlink",
43    "readlink",
44    "realpath",
45    "truncate",
46    "utimes",
47    "lutimes",
48    "mkdtemp",
49    "open",
50    "opendir",
51    "glob",
52];
53
54/// The `FileHandle` port (`fs_filehandle.js`), evaluated once: an object with
55/// `open`, `FileHandle`, and the handle forms of `readFile` / `writeFile`.
56fn file_handle_module() -> Result<Value, String> {
57    thread_local! {
58        static MODULE: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
59    }
60    if let Some(m) = MODULE.with(|m| m.borrow().clone()) {
61        return Ok(m);
62    }
63    let factory = crate::eval_internal(include_str!("fs_filehandle.js"))?;
64    let (node_error, cancel) = with_host(|h| {
65        (
66            h.alloc(crate::host::JsObj::Builtin("util.@@nodeError".into())),
67            h.alloc(crate::host::JsObj::Builtin(
68                "util.@@readableStreamCancel".into(),
69            )),
70        )
71    });
72    let made = crate::host::invoke(&factory, vec![node_error, cancel], None)?;
73    MODULE.with(|m| *m.borrow_mut() = Some(made.clone()));
74    Ok(made)
75}
76
77/// Call one of the port's functions by name.
78fn call_port(name: &str, args: Vec<Value>) -> Result<Value, String> {
79    let f = crate::builtins::get_property(&file_handle_module()?, name)?;
80    crate::host::invoke(&f, args, None)
81}
82
83/// `path instanceof FileHandle` — the test node's `readFile`/`writeFile` make
84/// before treating their first argument as a path. Only an ordinary object can
85/// be one; a string never reaches the port.
86fn is_file_handle(v: &Value) -> Result<bool, String> {
87    let plain = with_host(|h| matches!(h.get(v), Some(crate::host::JsObj::Object(_))));
88    if !plain {
89        return Ok(false);
90    }
91    let class = crate::builtins::get_property(&file_handle_module()?, "FileHandle")?;
92    let found = crate::host::call_method(&class, "isFileHandle", vec![v.clone()])?;
93    Ok(with_host(|h| h.truthy(&found)))
94}
95
96pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
97    if method == "open" {
98        return Some(call_port("open", args.to_vec()));
99    }
100    // A `FileHandle` in the path position reads or writes through the handle,
101    // from its current position (`readFileHandle` / `writeFileHandle`).
102    if matches!(method, "readFile" | "writeFile" | "appendFile") {
103        match is_file_handle(args.first().unwrap_or(&Value::Undef)) {
104            Ok(true) => {
105                let port = if method == "readFile" {
106                    "readFile"
107                } else {
108                    "writeFile"
109                };
110                return Some(call_port(port, args.to_vec()));
111            }
112            Ok(false) => {}
113            Err(e) => return Some(Err(e)),
114        }
115    }
116    // `options.signal`: validated, and an already-aborted one rejects with
117    // node's `AbortError` before any work. It was ignored.
118    if matches!(method, "readFile" | "writeFile" | "appendFile") {
119        let opts = args.get(if method == "readFile" { 1 } else { 2 });
120        if let Some(o) = opts.filter(|o| with_host(|h| h.type_of(o)) == "object") {
121            let refusal = match call_port("signalRefusal", vec![o.clone()]) {
122                Ok(r) => r,
123                Err(e) => return Some(Err(e)),
124            };
125            if !matches!(refusal, Value::Undef) {
126                let p = with_host(|h| h.new_promise());
127                let id = with_host(|h| h.promise_id(&p).unwrap_or(0));
128                crate::host::reject_promise_val(id, refusal);
129                return Some(Ok(p));
130            }
131        }
132    }
133    // Every other method delegates to the synchronous `fs` sibling of the same
134    // name, then wraps the outcome in a settled Promise.
135    let sync_name = match method {
136        "readFile" => "readFileSync",
137        "writeFile" => "writeFileSync",
138        "appendFile" => "appendFileSync",
139        "readdir" => "readdirSync",
140        "mkdir" => "mkdirSync",
141        "rmdir" => "rmdirSync",
142        "rm" => "rmSync",
143        "unlink" => "unlinkSync",
144        "stat" => "statSync",
145        "lstat" => "lstatSync",
146        "statfs" => "statfsSync",
147        "access" => "accessSync",
148        "rename" => "renameSync",
149        "copyFile" => "copyFileSync",
150        "cp" => "cpSync",
151        "chmod" => "chmodSync",
152        "chown" => "chownSync",
153        "lchown" => "lchownSync",
154        "link" => "linkSync",
155        "symlink" => "symlinkSync",
156        "readlink" => "readlinkSync",
157        "realpath" => "realpathSync",
158        "truncate" => "truncateSync",
159        "utimes" => "utimesSync",
160        "lutimes" => "lutimesSync",
161        "mkdtemp" => "mkdtempSync",
162        "opendir" => "opendirSync",
163        "glob" => "globSync",
164        _ => return None,
165    };
166    // The method itself always succeeds in *returning a Promise*; success/failure
167    // of the I/O is encoded in that Promise's settled state.
168    Some(Ok(settled(sync(sync_name, args))))
169}
170
171/// Run a synchronous `fs` method by name, returning its `Result` (the `Option`
172/// is always `Some` for the known sync names above).
173fn sync(sync_method: &str, args: &[Value]) -> Result<Value, String> {
174    super::fs::call(sync_method, args).unwrap_or_else(|| Err("Error: EIO: internal error".into()))
175}
176
177/// Wrap a synchronous outcome in an already-settled Promise: fulfilled with the
178/// value, or rejected with an `Error` synthesized from the message. The host
179/// borrow is released before `resolve`/`reject` (which re-enter the host).
180fn settled(result: Result<Value, String>) -> Value {
181    let p = with_host(|h| h.new_promise());
182    let id = with_host(|h| h.promise_id(&p).unwrap_or(0));
183    // The error is built now, while the stack it records is the caller's.
184    let outcome = match result {
185        Ok(v) => Ok(v),
186        Err(e) => Err(with_host(|h| crate::builtins::synth_error(h, &e))),
187    };
188    // node settles the promise when the thread-pool job completes, in the
189    // loop's poll phase — the same queue as a callback-form completion. It
190    // was settled here and now, so `fs.readFile(p, cb)` started before
191    // `fsPromises.readFile(p)` saw its callback run second.
192    with_host(|h| {
193        h.queue_io_native(Box::new(move || {
194            match outcome {
195                Ok(v) => crate::host::resolve_promise_val(id, v),
196                Err(ev) => crate::host::reject_promise_val(id, ev),
197            }
198            Ok(())
199        }))
200    });
201    p
202}