Skip to content

readline unexpected behavior #42581

@batrudinych

Description

@batrudinych

Version

10.24.1, 12.22.10, 14.19.1

Platform

Linux l1 5.15.25-1-MANJARO #1 SMP PREEMPT Wed Feb 23 14:44:03 UTC 2022 x86_64 GNU/Linux

Subsystem

No response

What steps will reproduce the bug?

  1. create in.txt file with the following contents:
1
  1. create a test.js file in the same directory and paste the following code snippet:
'use strict'

const fs = require('fs')
const readline = require('readline')

;(async function () {
  const inputFileName = './in.txt'
  const outputFileName = './out.txt'
  const inputReadStream = fs.createReadStream(inputFileName)
  const rl = readline.createInterface({
    input: inputReadStream,
    crlfDelay: Infinity
  })

  fs.open(outputFileName, 'w', (err, outFd) => {
    fs.appendFile(outFd, '0', async () => {
      for await (const line of rl) {
        fs.appendFileSync(outFd, line)
      }
      fs.close(outFd, () => {
        console.log('closed')
      })
    })
  })
})()
  1. execute the snippet: node test.js
  2. open out.txt file and verify the contents

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

always

What is the expected behavior?

the out.txt should contain 01

What do you see instead?

the out.txt file contains 0

Additional information

Script produces expected result with Node.js 16.14.2

Script returns expected results in case if synchronous versions of fs module functions are used

Additionally, if you modify the script in the following way, you'll get the expected result:

'use strict'

const fs = require('fs')
const readline = require('readline')

;(async function () {
  const inputFileName = './in.txt'
  const outputFileName = './out.txt'
  const inputReadStream = fs.createReadStream(inputFileName)

  fs.open(outputFileName, 'w', (err, outFd) => {
    fs.appendFile(outFd, '0', async () => {
      const rl = readline.createInterface({
        input: inputReadStream,
        crlfDelay: Infinity
      })
      for await (const line of rl) {
        fs.appendFileSync(outFd, line)
      }
      fs.close(outFd, () => {
        console.log('closed')
      })
    })
  })
})()

readline interface is created after the append operation.
resulting contents of out.txt:

01

Metadata

Metadata

Assignees

No one assigned

    Labels

    readlineIssues and PRs related to the built-in readline module.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions