How can I write to the NUL device under Windows from node.js?
Asked Answered
B

3

12

This is bugging me for several days now. I know about the standard stream redirection to the NUL device, but this isn't the case. node.js uses CreateFileW under its fs native/libuv bindings.

Unfortunately using something like:

require('fs').writeFileSync('NUL', 'foo')

creates a NUL file into the cwd that has 3 bytes.

I tried writing to the \Device\Null, but since I'm pretty much a *nix head where everything is a file, I failed to actually find a working path for \Device\Null. Such as \\.\Device\Null that throws ENOENT.

Any ideas about how to make this work under Windows?

This seems to be related, but I can not track the whole flow from lib/fs.js to uv/src/win/fs.c to check that the path argument doesn't suffer from some kind of relative to absolute path resolution.

Bibulous answered 15/6, 2012 at 15:41 Comment(2)
Note sure if it will work, but try 'NUL:'.Coronation
Tried it before posting the question. Does not work. Throws some kind of access denied error. Don't have a Windows machine at the moment to provide the specifics.Bibulous
V
7

Valid path to NUL device is "\\\\.\\NUL", not NUL, so the usage is: fs.writeFileSync("\\\\.\\NUL", "foo"). This issue was raised against Node.js on GitHub: https://github.com/nodejs/node-v0.x-archive/issues/9271

Since NUL is a device, not a file, it has to be accessed via device namespace - this requires putting \\.\ in the beginning (the other slashes are for escaping) - see https://msdn.microsoft.com/en-gb/library/windows/desktop/aa365247.aspx#Win32_Device_Namespaces.

There is also a simple dev-null library on NPM that can be used with streams: https://www.npmjs.com/package/dev-null (not with .writeFile though).

Vacillation answered 20/4, 2016 at 13:54 Comment(0)
G
3

There is a long workaround, like code it yourself. But you can take an idea from here https://github.com/hanshuebner/node-hid/blob/master/src/HID.cc and write a wrapper over C library.

Gail answered 17/6, 2012 at 21:51 Comment(2)
Instead of passing a wrapper method for the NUL device (which detects the OS and acts accordingly), I simply patched the library to not attach any data / end event listeners if null is passed as argument. I guess this is the easier way of doing things instead of letting the OS to discard the data.Bibulous
I glad you found a working solution. Can you share your code with community? :)Gail
A
1

Node.js provides a lookup for the correct OS path to the null device file, via the node:os native module:

https://nodejs.org/docs/latest/api/os.html#osdevnull

e.g. import { devNull } from 'node:os';

Anesthesiologist answered 9/3, 2024 at 12:56 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.