Node.js 检查文件是否存在

2024-02-08

如何检查文件是否存在?


考虑直接打开或读取文件,以避免竞争条件:

const fs = require('fs');

fs.open('foo.txt', 'r', (err, fd) => {
  // ...
});
fs.readFile('foo.txt', (err, data) => {
  if (!err && data) {
    // ...
  }
})

Using fs.existsSync https://nodejs.org/api/fs.html#fsexistssyncpath:

if (fs.existsSync('foo.txt')) {
  // ...
}

Using fs.stat https://nodejs.org/api/fs.html#fsstatpath-options-callback:

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);
  }
});

已弃用:

fs.exists https://nodejs.org/api/fs.html#fsexistspath-callback已弃用。

Using path.exists:

const path = require('path');

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

Using path.existsSync:

if (path.existsSync('foo.txt')) { 
  // ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Node.js 检查文件是否存在 的相关文章

随机推荐