Can I expose RawFd (via IntoRawFd) to v8 javascript API?

⚓ Rust    📅 2025-10-16    👤 surdeus    👁️ 2      

surdeus

Hi, I am trying to implement some "filesystem" javascript APIs with v8 javascsript engine. The "fs" APIs are similar to deno's API, the first API is async function open(filename, openOptions): FsFile. It returns a FsFile javascript object.

And the FsFile has many APIs:

  • read
  • writeAll
  • write
  • close
  • And a lot more......

When implement this, I will have to pass the file handler to javascript side. I found there are some APIs in rust std library:

Let's ignore the difference between Linux/Unix and Window file handler first, to make the discussion easier.

Passing data between rust and javascript is not easy, so I am thinking I could use IntoRawFd to get the raw fd from a std::fs::File (which is unsafe because it leaks resource). Then wrap this fd with the FsFile javascript object, so the FsFile is actually just:

/// javascript/typescript
export class FsFile {
  fd: number,

  async function read(): string {
    return await internal_fs_read_op(this.fd);
  }

  async function writeAll(payload: string) {
    await internal_fs_write_all(this.fd, payload);
  }

  async function close() {
    const fd = this.fd;
    this.fd = undefined;
    await internal_fs_close(fd);
  }
}

async function open(filename, openOptions): FsFile {
  const fd = await internal_fs_open_op(filename, openOptions);
  return { fd };
}

The question is, can I restore the std::fs::File with FromRawFd API in rust side, without losing any "context" inside std::fs::File? (Since I am not sure about rust std library internal implementation)

2 posts - 1 participant

Read full topic

🏷️ Rust_feed