2017-03-22 21 views
1

我是node.js的新手,试图绕着承诺努力工作。我正在尝试从文件中读取内容,返回承诺和文件内容。我到目前为止能够阅读文件的内容并在控制台上打印它们,并返回一个承诺。我想要返回文件的内容。退货承诺和内容(可能很多)

这是我的代码到目前为止。

function() { 
return fs.exists(listFile).then(function (exists) { 
    if(exists) { 
     return fs.readFile(listFile).then(function(response) { 
      console.log(response.toString()); 
     }).catch(function(error) { 
      console.error('failed to read from the file', error); 
     }); 
    } 
}).catch(function(err) { 
    console.error('Error checking existence', err) 
}); 
}; 
+0

回答类似的问题:http://stackoverflow.com/a/39761387/4175944 – Christopher

+3

您使用的蓝鸟? 'fs.exists()'不返回一个Promise。 – jessegavin

+0

[如何正确获取从承诺返回的值?]可能重复(http://stackoverflow.com/questions/39761302/how-to-correctly-get-the-value-returned-from-a-promise) – Christopher

回答

1

fs.readFile(listFile)返回一个承诺。这就是为什么你可以链接它后面的“.then()”方法。目前没有什么可以回报的。此外,它将返回到您在第二行传递给“.then”的回调函数。

要访问文件的内容,您需要调用另一个函数,并将文件内容直接打印到控制台。

function() { 
return fs.exists(listFile).then(function (exists) { 
    if(exists) { 
     fs.readFile(listFile).then(function(response) { 
      console.log(response.toString()); 
      handleFileContents(response.toString()); 
     }).catch(function(error) { 
      console.error('failed to read from the file', error); 
     }); 
    } 
}).catch(function(err) { 
    console.error('Error checking existence', err) 
}); 
}; 

function handleFileContents(content) { 
    // ... handling here 
} 
+1

@baao,OP使用'mz/fs',它返回承诺。 – zzzzBov

+0

Ahhhhhhh @zzzzBov,谢谢澄清 – baao

+0

@Lenco这是如何解决我不得不返回内容和承诺的问题?我将需要将文件内容传递给另一个承诺。 –

0

你不能return文件本身的内容,它们是异步检索。所有你能做的就是回到一个承诺内容:

function readExistingFile(listFile) { 
    return fs.exists(listFile).then(function (exists) { 
     if (exists) { 
      return fs.readFile(listFile).then(function(response) { 
       var contents = response.toString(); 
       console.log(contents); 
       return contents; 
//    ^^^^^^^^^^^^^^^^ 
      }).catch(function(error) { 
       console.error('failed to read from the file', error); 
       return ""; 
      }); 
     } else { 
      return ""; 
     } 
    }).catch(function(err) { 
     console.error('Error checking existence', err) 
     return ""; 
    }); 
} 

使用它像

readExistingFile("…").then(function(contentsOrEmpty) { 
    console.log(contentsOrEmpty); 
}); 

顺便说一句,using fs.exists like you did is an antipattern,而且它一般不推荐使用。忽略它,只是捕获错误从一个不存在的文件:

function readExistingFile(listFile) { 
    return fs.readFile(listFile).then(function(response) { 
     return response.toString(); 
    }, function(error) { 
     if (error.code == "ENOENT") { // did not exist 
      // … 
     } else { 
      console.error('failed to read from the file', error); 
     } 
     return ""; 
    }); 
}