0

I am trying to implement a simple Express handler which appends the request body to a file, and returns the offset in a file where the write has been performed. Based on some research, it seems that there is no ftell-like function in NodeJS, and the similar questions (like fs.createReadStream() at specific position of file) refer to using start parameter or manually seeking - which I do not see how to use in combination with appending to a file (when the offset at the end of a file is unknown). I am currently stuck with a code like

app.put('/:blob', (req, res) => {
  var blob = req.params.blob;
  var blobpath = path.join(__dirname, 'data/' + blob);
  var stream = fs.createWriteStream(blobpath, {flags:'a'});
  var pos = fs.tell(stream);  // <-- I do not know how to do this

  function handle(data) {
    stream.write(data);
    req.once('data', handle);
  }
  req.once('data', handle);
  req.on('end', function() {
    stream.end();
    res.json({offset: pos});
  });
});

Could you please help me how I should achieve my goal?

Karel Horak
  • 1,022
  • 1
  • 8
  • 19
  • Does this answer your question? [How to know file position in Node.js? - return value of lseek](https://stackoverflow.com/questions/58989723/how-to-know-file-position-in-node-js-return-value-of-lseek) – AKX Sep 26 '20 at 19:27
  • Unfortunately, as far as I understand the answer, `bytesWritten` only allows me to track number of bytes that I have written myself. Or does it allow me to obtain the number of bytes that has been written prior to opening the file? – Karel Horak Sep 26 '20 at 19:44
  • The point is that there doesn't seem to be a `ftell` sort of thing in Node. Of course if you believe you're the only writer of your file, you can `stat` the file first to get its length... – AKX Sep 26 '20 at 20:05

0 Answers0