0

I'm trying to get fs.read() to work but running into some issue(s). Here is my fread.js script:

var fs = require('fs');

fs.open('test.txt', 'r', function (err, handle) {

    var f = handle;
    var b = new Buffer(100000);

    fs.read(f, b, 0, 100000, null, function (err, bytesRead) {
        console.log(b.toSting("utf8", 0, bytesRead));
        fs.close(f);
    });

});

Why do I get the following TypeError: Bad Argument error upon running it?

$ node fread.js 

fs.js:457
  binding.read(fd, buffer, offset, length, position, wrapper);
          ^
TypeError: Bad argument
    at Object.fs.read (fs.js:457:11)
    at /home/max/dev/livelessons/fread.js:8:5
    at Object.oncomplete (fs.js:107:15)
4
  • @Cerbrus try checking the docs Commented Apr 28, 2014 at 12:14
  • @Scimonster: Oh, overlooked the function argument, I thought handle wasn't set anywhere. Commented Apr 28, 2014 at 12:16
  • 2
    Duplicating f and handle variables is unnecessarily btw. Commented Apr 28, 2014 at 12:16
  • Argg. So sorry for wasting all of your time. I was opening a non-existent file. test.txt should have been text.txt. Sure it was a bad argument but that error message gave me little clue as to where to find it. Commented Apr 28, 2014 at 12:35

2 Answers 2

4

The problem was that I gave it the wrong file name. test.txt should have been text.txt. Doh!

Sign up to request clarification or add additional context in comments.

Comments

2

You should check that fs.open() was successful first. Most likely err is set and handle is set to undefined, causing the "Bad Argument" error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.