Thursday, 8 June 2017

Node.js fs.createReadStream on file with no read permission

I have a Node.js program which makes a call to fs.createReadStream(). It works as intended except when trying to open a file that read permissions are denied on it gives no indicator that I am aware of. Since I am piping the stream into another writable stream, this causes issues because the data is not actually transferred an the program doesn't know and thus can't take the appropriate action.

I found options for "flags" in the documentation for fs.open() which shows that "r+" should cause it to fail if the file doesn't exist like "wx" should cause it to fail if writing to an existing file. In instances where it does exist and there are no read permissions it just returns an empty stream.

How can I cause fs.createReadStream() to throw and error or something to identify that the data is not actually being read, regardless of file existence?

var func = function(sourcefile, destfile) {
  var fs.lstat(sourcefile, function (error, stats) {
    try {
      var infile = fs.createReadStream(sourcefile, {
        "flags": "r+",
        "encoding": null,
        "fd": null,
        "mode": stats.mode,
        "autoClose": true
      });
    } catch (error) {
      console.log(error);
      return;
    }
    try {
      var outfile = fs.createReadStream(destfile, {
        "flags": "wx",
        "encoding": null,
        "fd": null,
        "mode": stats.mode,
        "autoClose": true
      });
    } catch (error) {
      console.log(error);
      return;
    }
    infile.pipe(outfile);
  });
};
//NOTE: the try catch hasn't actually done anything, I just hoped it would



via FatalKeystroke

No comments:

Post a Comment