var fs = require('fs');try {// Query the entrystats = fs.lstatSync('/the/path');
// Is it a directory?if (stats.isDirectory()) {// Yes it is}}catch (e) {// ...}
var fs = require('fs');
try {fs.accessSync(path, fs.F_OK);// Do something} catch (e) {// It isn't accessible}
// Or
fs.access(path, fs.F_OK, function(err) {if (!err) {// Do something} else {// It isn't accessible}});
var path = require('path');
var dirs = ['one', 'two', 'three'];
dirs.map(function(dir) {path.exists(dir, function(exists) {var message = (exists) ? dir + ': is a directory' : dir + ': is not a directory';console.log(message);});});
function fileExists(path) {
try {return fs.statSync(path).isFile();}catch (e) {
if (e.code == 'ENOENT') { // no such file or directory. File really does not existconsole.log("File does not exist.");return false;}
console.log("Exception fs.statSync (" + path + "): " + e);throw e; // something else went wrong, we don't have rights, ...}}
var fs = require("fs");
function exists(path){//Remember file access time will slow your program.try{fs.accessSync(path);} catch (err){return false;}return true;}
function fileExists(path){return new Promise((resolve, fail) => fs.access(path, fs.constants.F_OK,(err, result) => err ? fail(err) : resolve(result))//F_OK checks if file is visible, is default does no need to be specified.
}
async function doSomething() {var exists = await fileExists('filePath');if(exists){console.log('file exists');}}
if(fs.existsSync(<path_that_need_to_be_checked>)){// enter the code to excecute after the folder is there.}else{// Below code to create the folder, if its not therefs.mkdir('<folder_name>', cb function);}
您可以使用fs-额外(npm i fs-额外)及其fs.ensureFile或目录fs.ensureDir,因为fs.exists已被删除,fs.access不建议您在使用后编辑该文件"在调用fs.open()、fs.readFile()或fs.writeFile()之前,不要使用fs.access()检查文件的可访问性。这样做会引入竞争条件,因为其他进程可能会在两次调用之间更改文件的状态。相反,用户代码应直接打开/读取/写入文件并处理如果文件不可访问时引发的错误。