Node.js check if path is file or directory

前端 未结 6 1368
小蘑菇
小蘑菇 2020-12-12 09:23

I can\'t seem to get any search results that explain how to do this.

All I want to do is be able to know if a given path is a file or a directory (folder).

6条回答
  •  爱一瞬间的悲伤
    2020-12-12 09:57

    Here's a function that I use. Nobody is making use of promisify and await/async feature in this post so I thought I would share.

    const promisify = require('util').promisify;
    const lstat = promisify(require('fs').lstat);
    
    async function isDirectory (path) {
      try {
        return (await lstat(path)).isDirectory();
      }
      catch (e) {
        return false;
      }
    }
    

    Note : I don't use require('fs').promises; because it has been experimental for one year now, better not rely on it.

提交回复
热议问题