Node.js检查存在文件

Rom*_*tko 129 fs node.js

我如何检查文件的存在?

在该模块的文档中,fs有一个方法的描述fs.exists(path, callback).但是,据我所知,它检查是否只存在目录.我需要检查文件!

如何才能做到这一点?

Fox*_*Fox 215

为什么不尝试打开文件?fs.open('YourFile', 'a', function (err, fd) { ... }) 无论如何,一分钟搜索后试试这个:

var path = require('path'); 

path.exists('foo.txt', function(exists) { 
  if (exists) { 
    // do something 
  } 
}); 

// or 

if (path.existsSync('foo.txt')) { 
  // do something 
} 
Run Code Online (Sandbox Code Playgroud)

对于Node.js v0.12.x及更高版本

双方path.existsfs.exists已弃用

*编辑:

更改: else if(err.code == 'ENOENT')

至: else if(err.code === 'ENOENT')

Linter抱怨双重等于不等于三等于.

使用fs.stat:

fs.stat('foo.txt', function(err, stat) {
    if(err == null) {
        console.log('File exists');
    } else if(err.code === 'ENOENT') {
        // file does not exist
        fs.writeFile('log.txt', 'Some log\n');
    } else {
        console.log('Some other error: ', err.code);
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 现在阅读此内容的任何人(Node.js v0.12.x)请记住,`fs.exists`和`fs.existsSync`也已被弃用.检查文件存在的最佳方法是`fs.stat`,如上所述. (38认同)
  • `path.exists`实际上已被弃用,以支持`fs.exists` (10认同)
  • 从Node js文档来看,如果你打算在检查文件存在后打开文件,那么它似乎是最好的方法,就是实际打开它并处理错误(如果它不存在).因为您的文件可以在您的存在检查和打开功能之间删除... (8认同)
  • @Antrikshy`fs.existsSync`不再被删除,尽管`fs.exists`仍然是. (5认同)
  • 请删除答案的第一部分,该部分仅适用于节点<0.12(太旧了) (2认同)

Pau*_* Ho 47

同步执行此操作的更简单方法.

if (fs.existsSync('/etc/file')) {
    console.log('Found file');
}
Run Code Online (Sandbox Code Playgroud)

API文档说明existsSync工作原理:
通过检查文件系统来测试给定路径是否存在.

  • @Imeurs但https://nodejs.org/api/fs.html#fs_fs_existssync_path说:请注意,fs.exists()已弃用,但fs.existsSync()不是. (17认同)
  • `fs.existsSync(path)`现在已弃用,请参阅https://nodejs.org/api/fs.html#fs_fs_existssync_path.对于同步实现,建议使用`fs.statSync(path)`,请参阅我的回答. (11认同)
  • `fs.existsSync`已被弃用,但现在不再使用了. (8认同)
  • 同步“更容易”,但也明显更糟糕,因为你会阻塞整个进程等待 I/O 并且其他任务无法取得进展。拥抱承诺和异步,如果不平凡的话,应用程序可能必须使用它们。 (2认同)

mid*_*ido 39

stat的替代方案可能是使用新的fs.access(...):

缩小的短期承诺函数用于检查:

s => new Promise(r=>fs.access(s, fs.F_OK, e => r(!e)))
Run Code Online (Sandbox Code Playgroud)

样品用法:

let checkFileExists = s => new Promise(r=>fs.access(s, fs.F_OK, e => r(!e)))
checkFileExists("Some File Location")
  .then(bool => console.log(´file exists: ${bool}´))
Run Code Online (Sandbox Code Playgroud)

扩展承诺方式:

// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
  return new Promise((resolve, reject) => {
    fs.access(filepath, fs.F_OK, error => {
      resolve(!error);
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

或者如果你想同步这样做:

function checkFileExistsSync(filepath){
  let flag = true;
  try{
    fs.accessSync(filepath, fs.F_OK);
  }catch(e){
    flag = false;
  }
  return flag;
}
Run Code Online (Sandbox Code Playgroud)

  • 与简单的“fs.exists”相比,这段代码是如此丑陋......真的想知道为什么他们强迫我们使用这样的替代方案:'-( (6认同)
  • 赞成,这绝对是检测 Node.js 中是否存在文件的最现代(2018 年)方法 (4认同)
  • 是的,这是官方推荐的方法,可以简单地检查文件是否存在,并且之后不会进行操作。否则使用 open/write/read 并处理错误。https://nodejs.org/api/fs.html#fs_fs_stat_path_callback (2认同)

Дми*_*ьев 23

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

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

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

main();
Run Code Online (Sandbox Code Playgroud)

我们需要使用,fs.stat() or fs.access()因为fs.exists(path, callback)现在已被弃用

另一个好方法是fs-extra

  • 短几个字符,也许更容易阅读:`const fileExists = path => fs.promises.stat(path).then(() => true, () => false);` (10认同)

Man*_*ddy 19

2021 年 8 月

阅读完所有帖子后:

let filePath = "./directory1/file1.txt";

if (fs.existsSync(filePath)) {
    console.log("The file exists");
} else {
    console.log("The file does not exist");
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*lin 19

异步等待风格的简洁解决方案:

import { stat } from 'fs/promises';

const exists = await stat('foo.txt')
   .then(() => true)
   .catch(() => false);

Run Code Online (Sandbox Code Playgroud)

  • 如果您打算执行“await”,那么也执行“try”/“catch”... (4认同)

lme*_*urs 18

fs.exists(path, callback)fs.existsSync(path)现在已过时,见https://nodejs.org/api/fs.html#fs_fs_exists_path_callbackhttps://nodejs.org/api/fs.html#fs_fs_existssync_path.

为了同步测试文件的存在,可以使用ie.fs.statSync(path).fs.Stats如果文件存在,将返回一个对象,请参阅https://nodejs.org/api/fs.html#fs_class_fs_stats,否则将引发错误,该错误将被try/catch语句捕获.

var fs = require('fs'),
  path = '/path/to/my/file',
  stats;

try {
  stats = fs.statSync(path);
  console.log("File exists.");
}
catch (e) {
  console.log("File does not exist.");
}
Run Code Online (Sandbox Code Playgroud)

  • 您为fs.existsync提供的链接清楚地表明它不被弃用"请注意,fs.exists()已弃用,但fs.existsSync()不是.(fs.exists()的回调参数接受不一致的参数与其他Node.js回调.fs.existsSync()不使用回调.)" (9认同)

Ign*_*dez 12

V6之前的旧版本: 这是文档

  const fs = require('fs');    
  fs.exists('/etc/passwd', (exists) => {
     console.log(exists ? 'it\'s there' : 'no passwd!');
  });
// or Sync

  if (fs.existsSync('/etc/passwd')) {
    console.log('it\'s there');
  }
Run Code Online (Sandbox Code Playgroud)

UPDATE

V6的新版本:文档fs.stat

fs.stat('/etc/passwd', function(err, stat) {
    if(err == null) {
        //Exist
    } else if(err.code == 'ENOENT') {
        // NO exist
    } 
});
Run Code Online (Sandbox Code Playgroud)


Kou*_*Das 7

fs.exists自1.0.0以来已被弃用.你可以用fs.stat而不是那个.

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

这是fs.stats文档的链接


mik*_*eil 6

@Fox:很棒的答案!这里有一些扩展,有更多选项.这是我最近一直在使用的首选解决方案:

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.'
  );


}
Run Code Online (Sandbox Code Playgroud)

PS如果你还没有使用它,请查看fs-extra--非常好. https://github.com/jprichardson/node-fs-extra)


chr*_*isw 5

关于fs.existsSync()不推荐使用的评论有很多不正确;它不是。

https://nodejs.org/api/fs.html#fs_fs_existssync_path

请注意,不建议使用fs.exists(),但不建议使用fs.existsSync()。