Reputation:
I want to create Node.js module which provides direct disk access on Windows. It must be able to read, write and search physical drive or virtual device. Because built-in module fs
depends on native code written in C++
which uses system function CreateFile
which supports \\.\PhysicalDriveX
string as an argument to gain access to physical drive, I've tried to do the same in Node.js. My code works fine, application successfully opens disk for read and write access, but there are problems with read
and write
commands.
When I want to read whole sector, or multiple sectors from disk, it works and displays bytes correctly. But, when I try to read half of a sector or a few bytes, it displays error:
Error: EINVAL: invalid argument, read
at Error (native)
at Object.fs.readSync (fs.js:731:19)
It was not an unsolvable problem to me. I've improved my read
function, so it extends buffer to match ceiled requested sector size (i.e. if it needs to read disk from half of the first sector to half of the third sector, it will read whole first, second and third sector and then it will slice the buffer). In order to make it easier to use, I fixed the size of my buffer to 512 bytes, so the only argument of my read
and write
functions are sector number from which data will be read to buffer or in which data will be written from buffer. Function read
works properly and I can get bytes from any sector of the drive.
The real problem is my write
function. It can write data only to the first sector. If I try to write data to any other sector expect the first one, I get the following error:
Error: EPERM: operation not permitted, write
at Error (native)
at Object.fs.writeSync (fs.js:786:20)
I tried everything to get rid of this problem, but I coldn't. I tried to change drive, to change buffer size (extend it to cluster size instead of sector size), to use fs.write
instead of fs.writeSync
, I also tried to search online for solution, but I coldn't find an answer. In order to find out why it doesn't work, I debugged my program using built-in Node.js debugger. I found out that the thread suddenly jumps from fs.readSync
to Error
function without any reasonable explanation and the process terminates.
How can I properly use fs.writeSync
function to write any sector to a physical drive? Am I doing something wrong, or there is a problem with Node.js?
Upvotes: 2
Views: 2629
Reputation: 587
We released a native add on for Node.js yesterday with helpers and documentation for doing direct IO on Node.js (cross-platform):
https://github.com/ronomon/direct-io
I think in your case you might need to look into special write restrictions on Windows (and the need for FSCTL_LOCK_VOLUME
so that you can write to all sectors and not just the master boot record).
You also need aligned buffers.
The module will help you with both of these requirements.
Upvotes: 2