镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

fs.readSync throws EOF Error instead of returning 0 (Windows, if STDIN is a pipe) #35997

Description

@RomainMuller
  • Version: 14.15.0
  • Platform: Windows 10 x86_64
  • Subsystem: fs

What steps will reproduce the bug?

Given the following node script:

/// script.js
const fs = require('fs');

console.error('Node: ' + process.execPath);
console.error('Version: ' + process.version);
console.error('Platform: ' + process.platform);

console.error('process.stdin: ' + process.stdin.constructor.name);

const fd = 0; // STDIN
const buffer = Buffer.alloc(4_096);

let read;
do {
  read = fs.readSync(fd, buffer, 0, buffer.length, null);
  if (read != 0) {
      console.log('STDIN: ' + buffer.slice(0, read).toString('utf-8'))
  }
} while (read != 0);

console.log('EOF was (normally) reached.')

Will behave differently based on how it is invoked:

$ node script.js
Node: C:\Program Files\nodejs\node.exe
Version: v14.15.0
Platform: win32
process.stdin: ReadStream
Data!
STDIN: Data!
^Z
EOF was (normally) reached.


$ echo 'Data!' | node script.js
Node: C:\Program Files\nodejs\node.exe
Version: v14.15.0
Platform: win32
process.stdin: Socket
STDIN: Data!
internal/fs/utils.js:308
    throw err;
    ^

Error: EOF: end of file, read
    at Object.readSync (fs.js:592:3)
    at Object.<anonymous> (H:\repro\test\script.js:14:13)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47 {
  errno: -4095,
  syscall: 'read',
  code: 'EOF'
}

How often does it reproduce? Is there a required condition?

This issue happens 100% of the time when process.stdin is a Socket instance.

What is the expected behavior?

The expected and documented behavior is that fs.readSync returns 0 when EOF is reached.

What do you see instead?

Instead, an Error: EOF is thrown, which is unexpected.

Additional information

This problem was surfaced as users are starting to see failures on Windows at aws/aws-cdk#11314.

We have additionally seen issues where in similar conditions (process.stdin is a socket/pipe), attempting to perform fs.readSync on file descriptor 0 (aka STDIN), occasionally results in unexpected EAGAIN errors being thrown, which might be related. That was highlighted in aws/aws-cdk#5187 and we are currently working with a pretty ugly workaround that would be nice if removed (but that other issue is a lot more difficult to steadily reproduce, as it does not always trigger, and may be caused by side-effects of another operation).

Activity

  1. RomainMuller commented on Nov 6, 2020

    @RomainMuller
    Author

    The stack trace of the error points at the following code:

    node/lib/fs.js

    Lines 590 to 592 in c1da528

    const result = binding.read(fd, buffer, offset, length, position,
    undefined, ctx);
    handleErrorFromBinding(ctx);

    I basically expect the windows binding returns different codes for Socket than for ReadStream and in turn causes the difference in behavior.

  2. mmomtchev commented on Nov 9, 2020

    @mmomtchev
    Contributor

    You will get much better results with:

    /// script.js
    const fs = require('fs');
    
    console.error('Node: ' + process.execPath);
    console.error('Version: ' + process.version);
    console.error('Platform: ' + process.platform);
    
    console.error('process.stdin: ' + process.stdin.constructor.name);
    
    const buffer = Buffer.alloc(4_096);
    
    let read;
    do {
        read = fs.readFileSync('/dev/stdin', buffer, 0, buffer.length, null);
        if (read != 0) {
            console.log('STDIN: ' + buffer.slice(0, read).toString('utf-8'));
        }
    } while (read != 0);
    
    console.log('EOF was (normally) reached.');

    Don't fiddle with the 0, 1 and 2 file descriptors. They are open in non-blocking mode and libuv doesn't expect this when you are passing a file descriptor.

  3. RomainMuller commented on Nov 9, 2020

    @RomainMuller
    Author

    Hey @mmomtchev,

    read = fs.readFileSync('/dev/stdin', buffer, 0, buffer.length, null);

    This is interesting and all... But /dev/stdin is not a thing on Windows, and I cannot require WSL... 🤷🏻‍♂️
    Or does fs have some magic tricks to make it look like this is a file that exists?

  4. mmomtchev commented on Nov 9, 2020

    @mmomtchev
    Contributor

    No, you are right, I can't think of any easy way to synchronously read from stdin on Windows
    There are npm modules or you could go the async way
    There is an awful solution here http://corpus.hubwiz.com/2/node.js/3430939.html that will simulate blocking access, repeating the call on EAGAIN and breaking the loop on EOF

    But the real answer is that Node is built for async I/O

  5. RomainMuller commented on Nov 9, 2020

    @RomainMuller
    Author

    We already have the ugly code to loop on EAGAIN...
    Unfortunately, the use-case I have does not lend itself to async exchange here... As there are ordering guarantees I must maintain.

    The real thing I'm concerned with here, is how fs.readSync throws an EOF error... When it is documented to never do this and instead return 0.

  6. mmomtchev commented on Nov 9, 2020

    @mmomtchev
    Contributor

    It says that the descriptor you are passing must be opened in blocking mode.

  7. RomainMuller commented on Nov 9, 2020

    @RomainMuller
    Author

    It says that the descriptor you are passing must be opened in blocking mode.

    Where though?

    I'm looking at: https://nodejs.org/api/fs.html#fs_fs_readsync_fd_buffer_offset_length_position, and the only place on this page where a requirement for fd to be in blocking (or non-blocking for that matters) mode is on createReadStream and createWriteStream, none of which I am using...


    In any case, in light of your confirming that we are doing things likely to trip libuv in weird and awkward ways, I've been implementing a more comprehensive (dirty) workaround in aws/jsii#2238 that also catches the EOF error; which would buy us time to figure out if/how we can proceed without needing to do synchronous I/O on our STD{IN,OUT,ERR}...

  8. mmomtchev commented on Nov 9, 2020

    @mmomtchev
    Contributor

    @RomainMuller in fact, the stdin is not opened in non-blocking mode on Windows, that is the case only on Linux and OSX, so maybe there is a solution to your problem

  9. mmomtchev commented on Nov 9, 2020

    @mmomtchev
    Contributor

    On Windows libuv does not properly handle pipes when operating in file mode. I wonder if it is supposed to, because normally, there is a separate pipe mode, but it is a trivial change. In any case, this issue should be taken to https://github.com/libuv/libuv
    It happens because the writing process exits and closes the anonymous pipe.
    Feel free to open it there, referencing this issue.

    This is everything that is needed to make it work:

    --- a/deps/uv/src/win/fs.c
    +++ b/deps/uv/src/win/fs.c
    @@ -918,7 +918,7 @@ void fs__read(uv_fs_t* req) {
         SET_REQ_RESULT(req, bytes);
       } else {
         error = GetLastError();
    -    if (error == ERROR_HANDLE_EOF) {
    +    if (error == ERROR_HANDLE_EOF || error == ERROR_BROKEN_PIPE) {
           SET_REQ_RESULT(req, bytes);
         } else {
           SET_REQ_WIN32_ERROR(req, error);
    
  10. mmomtchev commented on Nov 9, 2020

    @mmomtchev
    Contributor

    But then again, you will end up with Windows-specific JS code, which is not the Node way

  11. mmomtchev commented on Nov 9, 2020

    @mmomtchev
    Contributor

    @ronag is this supposed to work?

  12. ronag commented on Nov 9, 2020

    @ronag
    Member

    Sorry, sync api's is not my area of expertise.

  13. mmomtchev commented on Nov 9, 2020

    @mmomtchev
    Contributor

    It is not specific to synchronous mode. This is getting stranger by the minute.
    On Linux this leaves stdin in non-blocking mode:

    const fs = require('fs');
    console.error('process.stdin: ' + process.stdin.constructor.name);
    (async () => {
        let read;
        read = fs.createReadStream(null, { fd: 0 })
        for await (const r of read)
            console.log(r)
        console.log('EOF was (normally) reached.')
    })();

    but this leaves it in blocking mode:

    const fs = require('fs');
    
    (async () => {
        let read;
        read = fs.createReadStream(null, { fd: 0 })
        for await (const r of read)
            console.log(r)
        console.log('EOF was (normally) reached.')
    })();

    The difference is accessing process.stdin.constructor.name. Adding a simple console.error doesn't change anything.

  14. mmomtchev commented on Nov 9, 2020

    @mmomtchev
    Contributor

    Easiest way to check if a file descriptor is in blocking or non-blocking mode is cat /proc/<pid>/fdinfo/<fd> - look at flags, the fourth digit from the right to the left will be 4 for non-blocking mode

  15. mmomtchev commented on Nov 9, 2020

    @mmomtchev
    Contributor

    @RomainMuller, please disregard what I said, it seems that Node has a problem with handling consistently stdin across different situations and different platforms

  16. 13 remaining items

  17. mmomtchev commented on Nov 18, 2020

    @mmomtchev
    Contributor

    @joyeecheung, the current solution when it comes to FDs 0, 1 and 2 is absolutely horrible - ie they tend to transparently switch from blocking to non-blocking, requiring the user to reimplement the async read loop in his code by eventually microsleeping... However me too (and I didn't take @mcollina word for granted, I spent some time reading/testing) I came to the conclusion that there is simply no other solution. I still think that Node should not incite people to write horrible code, so this should not be official 😄 , but jokes apart, people are using these FDs, and most of the time they don't even realize something very weird is going on.

    They only viable long-term solution I see is that libuv supports reading from regular files in non-blocking mode - something that would be totally useless except to give Node (and the user code) an uniform abstraction layer.

    When it comes to the lazy-loading - at this point it doesn't change anything to not do it - the user code will still have to expect these FDs to be in either mode.

    I will only try pushing a PR to libuv for the EOF problem on Windows - now that we all agree that reading from a pipe in file mode should be supported.

  18. joyeecheung commented on Nov 18, 2020

    @joyeecheung
    Member

    If the confusing part is that the FD switches from blocking to non-blocking once you access process.stdin etc. (due to lazy loading), I guess we could just do something early and make sure that the mode is consistently non-blocking for users (which is probably the old behavior).

  19. mmomtchev commented on Nov 18, 2020

    @mmomtchev
    Contributor

    Yes, it is exactly what made that issue so confusing for me. Changing this however this will have a detrimental performance effect on process creation for everyone and it won't really accomplish anything - the user will still need to support both blocking and non-blocking FDs

  20. vtjnash commented on Nov 18, 2020

    @vtjnash
    Contributor

    Changing it to non-blocking is often likely going to be problematic for any native C libraries that nodejs interacts with, as well as any programs that are execv from nodejs. Thus, I don't recommend doing that. It's also potentially quite problematic in the (very infrequent) case where some other external library calls dup2 to replace the stdio handles with something else.

  21. mmomtchev commented on Nov 18, 2020

    @mmomtchev
    Contributor

    Me too, as an old-school UNIX guy, I was initially appalled by the design decision to have a non-blocking stdio - it is something that is known to break things. But how do you implement pipes in libuv? They are currently built around net.Socket and net.Socket is always in non-blocking mode. And at this point it is not even about blocking or non-blocking - it is about it being sometimes blocking and sometimes non-blocking - which is the major problem. But having a consistent stdio requires that libuv fully supports both files, pipes and ttys in one of those modes - which is not the case. You are libuv, would you consider a PR that adds a completely useless support for blocking I/O on pipes/sockets/ttys (through threads) or non-blocking supports for files (that actually blocks and also requires threads)? And the only reason for doing it would be to have a consistent stdio in Node across all platforms? I am not sure it is worth the effort.
    By the way, while researching this, I stumbled upon an effort by DJ Bernstein to standardize a new POSIX file API - that will have separate read_nonblocking / write_nonblocking calls instead of a flag attached to the descriptor. There was even an attempt to implement it in Linux (readv2 / writev2 calls) but the PR has been frozen for years.

  22. bughit commented on Nov 24, 2020

    @bughit

    the following patch appears to work (tested with piped curl)

    fs.readSync = function(origReadSync) {
      return function newReadSync() {
        try {
          return origReadSync.apply(this, arguments);
        } catch (e) {
          if (e.code === 'EOF')
            return 0;
          else
            throw e;
        }
      };
    }(fs.readSync);
  23. mmomtchev commented on Nov 24, 2020

    @mmomtchev
    Contributor

    @bughit it is a remarkably ugly solution, so I think it will be very appropriate to include it in the read loop with the microsleep 😄
    @RomainMuller there is a work around for your issue, this is libuv, so the final fix won't happen before Node 16

  24. added
    fsIssues and PRs related to file-system APIs and the fs module.
    on Dec 16, 2020
  25. added a commit that references this issue on May 14, 2021
  26. shnooshnoo commented on Nov 28, 2023

    @shnooshnoo

    Hi @RomainMuller, I wanted to look into this issue, but was not able to reproduce (tried 18.18.2, 20.10.0 and 22.0.0-pre). Do you think this can be closed now?

  27. StefanStojanovic commented on Jul 17, 2024

    @StefanStojanovic
    Contributor

    Since this is no longer reproducible, and there has been no answer since the last comment, I'll close this. If you still experience the same issue, please reopen this issue or open a new one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    fsIssues and PRs related to file-system APIs and the fs module.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions