var fs = require('fs'); fs.stat('path/to/file', function(err) { if (!err) { console.log('file or directory exists'); } else if (err.code === 'ENOENT') { console.log('file or directory does not exist'); } });
在这里,我们必须将函数调用包装在一个try/catch块中以处理错误。
var fs = require('fs'); try { fs.statSync('path/to/file'); console.log('file or directory exists'); } catch (err) { if (err.code === 'ENOENT') { console.log('file or directory does not exist'); } }