如何检查文件是否存在?


当前回答

@狐狸:回答得好! 这里有一个扩展,有更多的选项。这是我最近一直在使用的解决方案:

var fs = require('fs');

fs.lstat( targetPath, function (err, inodeStatus) {
  if (err) {

    // file does not exist-
    if (err.code === 'ENOENT' ) {
      console.log('No file or directory at',targetPath);
      return;
    }

    // miscellaneous error (e.g. permissions)
    console.error(err);
    return;
  }


  // Check if this is a file or directory
  var isDirectory = inodeStatus.isDirectory();


  // Get file size
  //
  // NOTE: this won't work recursively for directories-- see:
  // http://stackoverflow.com/a/7550430/486547
  //
  var sizeInBytes = inodeStatus.size;

  console.log(
    (isDirectory ? 'Folder' : 'File'),
    'at',targetPath,
    'is',sizeInBytes,'bytes.'
  );


}

另外,如果你还没有用过fs-extra,那就试试吧——它真的很贴心。 https://github.com/jprichardson/node-fs-extra)

其他回答

vannilla Nodejs 回调

function fileExists(path, cb){
  return fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result)) //F_OK checks if file is visible, is default does no need to be specified.
}

文档说你应该使用access()来代替已弃用的exists()

带有内置承诺的Nodejs (node 7+)

function fileExists(path, cb){
  return new Promise((accept,deny) => 
    fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result))
  );
}

流行的javascript框架

fs-extra

var fs = require('fs-extra')
await fs.pathExists(filepath)

如你所见,简单多了。与promisify相比,它的优势在于你可以使用这个包实现完整的类型(完整的智能感知/typescript)!大多数情况下,您已经包含了这个库,因为(+-10.000)其他库都依赖于它。

fs。Exists自1.0.0以来已弃用。你可以用fs。用统计代替。

var fs = require('fs');
fs.stat(path, (err, stats) => {
if ( !stats.isFile(filename) ) { // do this 
}  
else { // do this 
}});

这里是文档的链接 fs.stats

现代异步/等待方式(Node 12.8. net)。x)

const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));

const main = async () => {
    console.log(await fileExists('/path/myfile.txt'));
}

main();

我们需要使用fs.stat()或fs.access(),因为fs。Exists (path, callback)现在已弃用

另一个好方法是fs-extra

使用util的异步/等待版本。从节点8开始承诺:

const fs = require('fs');
const { promisify } = require('util');
const stat = promisify(fs.stat);

describe('async stat', () => {
  it('should not throw if file does exist', async () => {
    try {
      const stats = await stat(path.join('path', 'to', 'existingfile.txt'));
      assert.notEqual(stats, null);
    } catch (err) {
      // shouldn't happen
    }
  });
});

describe('async stat', () => {
  it('should throw if file does not exist', async () => {
    try {
      const stats = await stat(path.join('path', 'to', 'not', 'existingfile.txt'));
    } catch (err) {
      assert.notEqual(err, null);
    }
  });
});

以前,在坐下之前,我总是检查一下椅子是否在那里,然后再坐下,否则我有一个替代计划,比如坐在教练上。现在node.js站点建议直接go(不需要检查),答案是这样的:

    fs.readFile( '/foo.txt', function( err, data )
    {
      if(err) 
      {
        if( err.code === 'ENOENT' )
        {
            console.log( 'File Doesn\'t Exist' );
            return;
        }
        if( err.code === 'EACCES' )
        {
            console.log( 'No Permission' );
            return;
        }       
        console.log( 'Unknown Error' );
        return;
      }
      console.log( data );
    } );

代码从http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/从2014年3月,并略有修改,以适应计算机。它也会检查权限—删除测试chmod a-r foo.txt的权限