最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I find out whether a file is within a directory with Node.js? - Stack Overflow

programmeradmin3浏览0评论

Given two absolute or relative paths, A and B, I want to find out whether B is "inside of" the directory A—not just in the directory itself, but potentially in a subdirectory. I'd like to do this without a potentially huge number of fs.readdir calls.

For instance, if A is / and B is /foo/bar/baz, it should be pretty obvious that B is within A; the recursive readdir approach would be extremely inefficient.

One obvious idea is to convert both paths to absolute form, then check if the string form of B's absolute path starts with the string form of A's. However, there are two problems:

  1. How do you convert the relative paths to absolute paths?
  2. What about symbolic links and such?

I'll accept answers that make calls to Linux utilities (other than rm -rf... which technically could be used to solve the problem) or third-party Node libraries.

Given two absolute or relative paths, A and B, I want to find out whether B is "inside of" the directory A—not just in the directory itself, but potentially in a subdirectory. I'd like to do this without a potentially huge number of fs.readdir calls.

For instance, if A is / and B is /foo/bar/baz, it should be pretty obvious that B is within A; the recursive readdir approach would be extremely inefficient.

One obvious idea is to convert both paths to absolute form, then check if the string form of B's absolute path starts with the string form of A's. However, there are two problems:

  1. How do you convert the relative paths to absolute paths?
  2. What about symbolic links and such?

I'll accept answers that make calls to Linux utilities (other than rm -rf... which technically could be used to solve the problem) or third-party Node libraries.

Share Improve this question asked May 4, 2011 at 18:56 Trevor BurnhamTrevor Burnham 77.4k33 gold badges164 silver badges199 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10
var fs = require('fs');

var a = fs.realpathSync('/home/mak/www'); // /var/www
var b = fs.realpathSync('/var/www/test/index.html');

var b_in_a = b.indexOf(a) == 0;

var a_is_dir = fs.statSync(a).isDirectory();

fs.*Sync also have asynchronous versions, see fs module.

fs.realpathSync and fs.statSyncwill throw if the path does not exist.

I suggest this:

const path = require('path')

function isWithin(outer, inner) {
    const rel = path.relative(outer, inner);
    return !rel.startsWith('../') && rel !== '..';
}

It uses path.relative to pute the path of inner relative to outer. If it's not contained, the first ponent of the resulting path will be .., so that's what we check for.

发布评论

评论列表(0)

  1. 暂无评论