【问题标题】:specify whether or not a file exists in node.js指定 node.js 中是否存在文件
【发布时间】:2018-07-21 20:42:48
【问题描述】:

我使用此代码来指定文件是否存在:

if(fs.exists('../../upload/images/book/2.jpg')){
    console.log("yes the file exist");
} else{
        console.log("there is no file");
      }  

当文件在那里时,它总是说它不存在(没有文件) 我也使用fs.stat(...),但它再次给出了结果(没有文件)

文件夹结构:

root_app  
--------|.tmp  
--------|api  
------------|controllers  
------------------------|BookContoller.js (My code run from here)
--------|...(And the rest of the folders)  
--------|upload  
---------------|images  
----------------------|book  
---------------------------|2.jpg

谢谢

【问题讨论】:

  • 您从哪里调用此代码,您能否通过编辑您的问题向我们展示,以包含应用程序结构和文件位置以及相对于上传文件夹的代码?
  • 我建议看看这个console.log(path.resolve('../../upload/images/book/2.jpg')),看看它到底是什么绝对路径。注意:您必须先执行const path = require('path') 才能加载path 模块。
  • 还取决于您使用的节点版本,fs.exists() 已弃用
  • @chridam 我编辑了我的问题,我的节点版本是 9.4.0,sails.js 是 v 0.12.14
  • .. 内容将与当前目录相关,这取决于您如何启动 node.js 应用程序。如果您希望某些内容与模块目录相关,则应使用 __dirname 作为路径的基本部分。

标签: node.js sails.js


【解决方案1】:

fs.exists 是异步的。要使您的代码正常工作,您只需将其更改为 fs.existsSync

另外你的文件路径错误,你需要使用path.resolve__dirname,这样脚本就会知道在哪里找到文件。

if(fs.existsSync(path.resolve('../../upload/images/book/2.jpg'))) {

查看文档:

【讨论】:

  • 没有影响
  • @mascm 您还需要使用path.resolve__dirname 来获取文件的完整路径,请参阅更新后的答案。
  • 我已经测试过了,还是说文件不存在。 path.resolve找我:C:\Users\My user name\Desktop\upload\images\book\2.jpg
【解决方案2】:

我的问题解决了。
显然,我们应该使用 fs.accessSync() OR fs.access() 而不是 fs.exists()
Check out this link

也可以执行此过程:

function Custom_existsSync(filename) {
  try {
    fs.accessSync(filename);
    return true;
  } catch(ex) {
    return false;
  }  

if(Custom_existsSync(filename)){
    ....
}  

感谢所有帮助过我的人

【讨论】:

  • fs.exists 不返回值。只有传递给回调fs.exists(path, (result) => {});才能得到结果
猜你喜欢
  • 2013-07-15
  • 1970-01-01
  • 2021-01-28
  • 2013-11-09
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 2012-05-26
相关资源
最近更新 更多