Node.js promisifaction error

2019-09-16 15:38发布

问题:

Created a file name big.file and stored values:

const fs = require('fs');
const file = fs.createWriteStream('./big.file');

for(let i=0; i<= 2; i++) {
  file.write('1\n2\n3');
}
file.end()

Tried promisifaction, but I am not sure is this way or not.

function readFile('./big.file','utf8'){
    return new Promise(function(resolve,reject){
        fs.readFile('./big.file', 'utf8',function(err,data){
            if(err) reject (err);
            else{
                console.log(data);
                const lines =data.split('\n');
                console.log(lines);
                const numbers = lines.map(Number);
                const oddNumbers = numbers.filter(n => n%2 === 1);
                console.log('Odd numbers count:', oddNumbers.length);   
            } 
        });
    });
};

回答1:

You need to call resolve callback with the data, when there is no error.

function readFile(filename, encoding) {
    return new Promise(function(resolve, reject) {
        fs.readFile(filename, encoding, function(err, data) {
            if (err) {
              return reject (err);
            }
            console.log(data);
            const lines =data.split('\n');
            console.log(lines);
            const numbers = lines.map(Number);
            const oddNumbers = numbers.filter(n => n%2 === 1);
            console.log('Odd numbers count:', oddNumbers.length);
            resolve(oddNumbers);
        });
    });
};


回答2:

You are very close, but you are defining your function incorrect. Try this:

const fs = require('fs')
function readFile(fileName='./big.file', encoding='utf8'){
    return new Promise(function(resolve,reject){
        fs.readFile(fileName, encoding,function(err,data){
            if(err) reject (err);
            else{
                console.log(data);
                const lines =data.split('\n');
                console.log(lines);
                const numbers = lines.map(Number);
                const oddNumbers = numbers.filter(n => n%2 === 1);
                console.log('Odd numbers count:', oddNumbers.length);
            }
        });
    });
};

module.exports = {readFile}
readFile()


回答3:

You forgot to 'resolve' your promise. You need to invoke resolve(...) with parameters that you want to return as your promise results.

function readFile(fileName,encoding){
    return new Promise(function(resolve,reject){
        fs.readFile(fileName, encoding, function callback(err,data){
            if(err) reject (err);
            else {
                // this is your "return" statement
                resolve(data);
            } 
        });
    });
};

So that when you use it you can use then like:

readFile( './big.file', 'utf8' )
.then( function( data ){
  // count numbers...
})
.catch( function( err ){
    alert( err );
});