-1

Can you please explain what is wrong in this code below.

   var promise = fs.readFile(file);

   var promise2 = promise.then(function(data){
      var base64 = new Buffer(data, 'binary').toString('base64');
      res.end("success");
   }, function(err){
      res.end("fail");
   });

Its throwing error as TypeError: Cannot call method 'then' of undefined

Mithun Shreevatsa
  • 3,588
  • 9
  • 50
  • 95
  • 2
    `readFile` does not return a promise, why do you think it does? – Bergi Sep 10 '15 at 12:43
  • I am trying for base64 encryption of file as you can see, but i am new to promises. Then what would be the ideal of handling this scenario? – Mithun Shreevatsa Sep 10 '15 at 12:44
  • @Mithun you pass in a callback as described [here](https://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback) Also "but i am new to promises", maybe, but again, there is no promise involved here. – ci_ Sep 10 '15 at 12:45
  • @Mithun: Have a look at [How do I convert an existing callback API to promises?](http://stackoverflow.com/q/22519784/1048572) – Bergi Sep 10 '15 at 13:06

2 Answers2

2

readFile doesn't return a promise. The NodeJS by and large predates widespread use of promises and mostly uses simple callbacks instead.

To read the file, you pass in a simple callback, as this example from the documentation shows:

fs.readFile('/etc/passwd', function (err, data) {
  if (err) throw err;
  console.log(data);
});

There is a promisify-node module available that wraps standard NodeJS modules in a promise-enabled API. Example from its docs:

var promisify = require("promisify-node");
var fs = promisify("fs")
fs.readFile("/etc/passwd").then(function(contents) {
  console.log(contents);
});

I should emphasize that I don't know it and haven't used it, so I can't speak to how well it does its job. It appears to use nodegit-promise, a "Bare bones Promises/A+ implementation with synchronous inspection" rather than JavaScript's Promise (which is only fair; it predates JavaScript's Promise by a couple of years).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

You have to create an Async function which returns a promise or use a promise library like bluebird.js

Vanilla JS

 var promise = readFileAsync();
    promise.then( function(result) {
        // yay! I got the result.
    }, function(error) {
        // The promise was rejected with this error.
    }

    function readFileAsync()
    {
       var promise = new Promise.Promise();
       fs.readFile( "somefile.txt", function( error, data ) {
            if ( error ) {
                promise.reject( error );
            } else {
                promise.resolve( data );
            }
        });

        return promise;
    }

With BlueBird.js

 var Promise = require("bluebird"); 
 var fs = Promise.promisifyAll(require("fs"));

    fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) {
        console.log("Successful json");
    }).catch(SyntaxError, function (e) {
        console.error("file contains invalid json");
    }).catch(Promise.OperationalError, function (e) {
        console.error("unable to read file, because: ", e.message);
    });
ram hemasri
  • 1,624
  • 11
  • 14