Krishna Karki
Krishna Karki

Reputation: 797

node.js then() not working

I am new to node.js so I am trying to understand promises and wait on node.js. I want to print the file note.txt.

Here is my code

    var fs = require('fs');

    fs.readFile('note.txt','utf8').then(contents => console.log(contents))
    .catch(err => console.error(err));

When I run above code. I get the following error.

fs.readFile('note.txt','utf8').then(contents => console.log(contents))

    TypeError: Cannot read property 'then' of undefined
        at Object.<anonymous> (/Applications/nodeApps/test/index.js:13:31)
        at Module._compile (module.js:635:30)
        at Object.Module._extensions..js (module.js:646:10)
        at Module.load (module.js:554:32)
        at tryModuleLoad (module.js:497:12)
        at Function.Module._load (module.js:489:3)
        at Function.Module.runMain (module.js:676:10)
        at startup (bootstrap_node.js:187:16)
        at bootstrap_node.js:608:3

And I try another method for the same thing.

var fs = require('fs');

async function  read_file(){
  var file_data = await  fs.readFile('note.txt','utf8');
    return file_data;

}
console.log(read_file());

And I get following error

Promise { <pending> }
(node:6532) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

I get the same error when I run with --harmony. I m not sure if there is bug on my code or what is wrong. Please help me understand.

My Environment Node version: v8.9.0

node -p process.versions.v8: 6.1.534.46

Upvotes: 1

Views: 1972

Answers (4)

Imen Souissi
Imen Souissi

Reputation: 1

try to use the async await

function (async  err => {
    if (err) {
       console.err ....}

    await .... <other function included or comes after then .>
    await ... <other function included>
})

Upvotes: 0

hong4rc
hong4rc

Reputation: 4113

If you use NodeJs v10, try fs.promises:

var fs = require('fs').promises; // v10.0 use require('fs/promises')

fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));

If not, use readFileSync:

// This code can use for node v10 or lowwer
var fs = require('fs');

var data = fs.readFileSync('a.json');
console.log(data);

Upvotes: 1

Krishna Karki
Krishna Karki

Reputation: 797

Thank you for the answers. I learned that function must return promise in order to use then() and catch(). So the code should be like this

var fs = require('fs');

  function  read_file(){
    return new Promise(function(resolve, reject) {
         fs.readFile('note.txt','utf8',function(err,file){
            if(err){
                return reject(err);
            }else{
                resolve(file);
            }
        });
    });


}

read_file().then(
    (data)=>{
        console.log('success: '+data);
    }
).catch((err)=>{
    console.log('error: ',err);
});

Upvotes: 1

MrPooh
MrPooh

Reputation: 59

You're getting errors because fs.readfile doesn't return a promise; hence then doesn't exist. For you to use the function as a promise, you will need to wrap it up as a promise; you could use something like bluebird or Q.

Upvotes: 1

Related Questions