Node. js to determine whether a file exists

  • 2021-08-06 20:56:49
  • OfStack

Record some small knowledge points in the application of Node. js. If you find that many answers given by Google/Baidu "Node. js are still fs. exists, fs. exists is not recommended here. You can choose fs. stat or fs. access.

Why not recommend fs. exists

When we design a callback function, we usually follow a principle of "error-first callback function", that is, the first parameter of the return value is an error message to verify whether there is an error, and other parameters are used to return data.

The following example shows the use of fs. exists, which directly returns a Boolean value, violating the 1 design principle of "error-first callback function", which is one reason.


fs.exists('/etc/passwd', (exists) => { 
 console.log(exists ? ' Existence ' : ' Nonexistent '); 
}); 

The other one is not recommended to use fs. exists () to determine whether a file exists before fs. open (), fs. readFile () or fs. writeFile (), because this will cause race conditions. If it is in multi-process, the execution of the program is not completely linear. When one process of the program is executing fs. exists and fs. writeFile (), other processes may change the state of the file in between, which will cause some unexpected results.

Not recommended:


(async () => { 
 const exists = await util.promisify(fs.exists)('text.txt'); 
 console.log(exists); 
 await sleep(10000); 
 if (exists) { 
  try { 
   const res = await util.promisify(fs.readFile)('text.txt', { encoding: 'utf-8' }); 
   console.log(res); 
  } catch (err) { 
   console.error(err.code, err.message); 
   throw err; 
  } 
 } 
})(); 

Recommended:


(async () => { 
 try { 
  const data = await util.promisify(fs.readFile)('text.txt', { encoding: 'utf-8' }); 
  console.log(data); 
 } catch (err) { 
  if (err.code === 'ENOENT') { 
   console.error('File does not exists'); 
  } else { 
   throw err; 
  } 
 } 
})(); 

At present, fs. exists has been abandoned. In addition, it needs to be clear that only when the file is not directly used, check whether the file exists. The following recommendations are several methods to check whether the file exists.

Using fs. stat

fs. stat returns an fs. Stats object that provides a lot of information about the file, such as file size, creation time, and so on. Two methods, stats. isDirectory (), stats. isFile (), are used to determine whether it is a directory or a file.


const stats = await util.promisify(fs.stat)('text1.txt'); 
console.log(stats.isDirectory()); // false 
console.log(stats.isFile()); // true 

If you are just checking the existence of a file, the following fs. access is recommended.

Using fs. access

fs. access receives an mode parameter to judge whether a file exists, is readable and is writable, and the return value is an err parameter.


const file = 'text.txt'; 
 
//  Check whether the file exists in the current directory.  
fs.access(file, fs.constants.F_OK, (err) => { 
 console.log(`${file} ${err ? ' Nonexistent ' : ' Existence '}`); 
}); 
 
//  Check whether the file is readable.  
fs.access(file, fs.constants.R_OK, (err) => { 
 console.log(`${file} ${err ? ' Unreadable ' : ' Readable '}`); 
}); 
 
//  Check whether the file is writable.  
fs.access(file, fs.constants.W_OK, (err) => { 
 console.log(`${file} ${err ? ' Unwritable ' : ' Writable '}`); 
}); 
 
//  Check whether the file exists in the current directory and is writable.  
fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => { 
 if (err) { 
  console.error( 
   `${file} ${err.code === 'ENOENT' ? ' Nonexistent ' : ' Readable only '}`); 
 } else { 
  console.log(`${file}  Existing and writable `); 
 } 
}); 

Similarly, it is not recommended to use fs. exists () to determine whether a file exists before fs. open (), fs. readFile (), or fs. writeFile (), which will cause a race condition.

Reference

http://nodejs.cn/api/fs.html

The above is Node. js to determine whether a file exists in detail, more about Node. js to determine whether the file exists, please pay attention to other related articles on this site!


Related articles: