How to timeout an fs.read in node.js?

Viewed 3503

I try to read from a filedescriptor with fs.read. The callback-function is called after it got the data. It's working fine.

But now I want to implement a timeout mechanism: If the fs.read does not get data within the timeout it should stop reading.

How can I tell fs.read to stop reading? It is still hanging in the background trying to read.

I do roughly the following:

...
var fd = fs.openSync("/dev/ttyUSB0", 'rs+');
...
...
var bout = new Buffer(string,'binary');
fs.write(fd, bout, 0, bout.length,undefined,function(err, written, buffer) {
  console.log("error writing: "+err);

  var bin = new Buffer(1);
  fs.read(fd,bin,0,1,undefined,function(err,read,buffer) {
    console.log("got it: "+bin);
  });
});
...
...

I want to write something to /dev/ttyUSB0 and read an answer, but sometimes there is no answer. If this happens, the read should timeout so that I can start another write/read.

Thanks

I tried to do it with Timeout and close, but it is not working, here is an example: You have to make "mkfifo file" for the test.

var fs=require('fs');

console.log("open file");

fs.open('file', 'r+', function(err,fd) {

  console.log("start reading on "+fd);

  var length=5;

  var data = new Buffer(length);
  data.fill("-");

  setTimeout(function(){
    console.log("timeout");
    console.log("close fd "+fd);
    fs.close(fd,function(err) {
      console.log("close done: "+err);
    });
  }, 5000);

  fs.read(fd, data, 0, length,undefined, function(error, got) {
    console.log("error: "+error);
    console.log("got callback: "+data);
  });

  console.log("done");
});

The fs.close does not work. After it has closed you can make a "echo test > file" and then the read get the data. Reading on a closed Filehandle?

Any Idea?

6 Answers

fs.readSync with timeout, using child_process.spawnSync to call dd

calling dd (max RSS 4 MB) is cheaper than calling node (max RSS 40 MB)

unix only. on windows this may work with busybox dd

// readWithTimeout.js

const child_process = require('child_process');
const fs = require('fs');

/**
* read with timeout. unix only
* @param {number | string} fdOrPath
* @param {number} blockSize
* @param {number} timeout
* @param {Object} options
* @param {number} [options.numBlocks=1]
* @param {string=} options.encoding
*/
function readWithTimeout(fdOrPath, blockSize, timeout, options = {}) {
  if (!options) options = {};
  const numBlocks = options.numBlocks || 1;
  if (options.numBlocks) delete options.numBlocks;
  if (options.timeout) throw Error('dont set options.timeout');
  const ddArgs = [`bs=${blockSize}`, `count=${numBlocks}`, 'status=none'];
  const stdio = [fdOrPath, 'pipe', 'pipe'];
  if (typeof fdOrPath == 'string') {
    if (!fs.existsSync(fdOrPath)) throw Error(`no such file: ${fdOrPath}`);
    ddArgs.push(`if=${fdOrPath}`);
    stdio[0] = null;
  }
  else if (typeof fdOrPath != 'number') {
    throw Error(`fdOrPath must be number or string`);
  }
  //console.dir({ fdOrPath, blockSize, timeout, stdio, ddArgs });
  const reader = child_process.spawnSync('dd', ddArgs, {
    timeout,
    stdio,
    windowsHide: true,
    ...options,
  });
  if (reader.error) throw reader.error;
  return reader.stdout;
}

// demo: read (1 byte) token from gnumake jobserver on fd 3
try {
  const readLen = 1;
  const output = readWithTimeout(3, 1, 1000, {
  //const output = readWithTimeout('/dev/null', 1, 1000, {
    encoding: 'utf8',
  });
  if (output.length == 0) {
    console.log(`read nothing`);
  }
  else if (output.length < readLen) {
    console.log(`read partial: ${output.length} of ${readLen} bytes`);
  }
  else {
    console.log('read ok');
  }
  console.dir(output);
}
catch (e) {
  if (e.errno == -110) {
    console.log('read error: timeout');
  }
  else {
    console.log('read error:');
    console.dir(e);
  }
}
# Makefile
# note: single space after $(.RECIPEPREFIX)
.RECIPEPREFIX := $(.RECIPEPREFIX) 

all:
  +node readWithTimeout.js
  +node readWithTimeout.js
  +node readWithTimeout.js
  +node readWithTimeout.js
$ make -j3

node readWithTimeout.js
read ok
'+'
node readWithTimeout.js
read ok
'+'
node readWithTimeout.js
read error: timeout
node readWithTimeout.js
read error: timeout
make: INTERNAL: Exiting with 1 jobserver tokens available; should be 3!

+node tells make to run node with make jobserver

make says "should be 3" because we did not write the tokens back to the jobserver on fd 4

this is part of my gnumake-tokenpool for javascript

code also in read-with-timeout

based on the answer by verybadalloc

Related