考虑直接打开或读取文件,以避免竞争条件:
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')) {
// ...
}