我正在处理 MQTT handler我想为每个有事件监听器的父目录发出一个事件。例如:
如果有以下可用的 MQTT 路径,其中有下标——这些路径有事件监听器——
测试
回复者/请求
测试/回复/请求
有人在主题 test/replyer/request/@issuer
上发布,应该有 2 个事件发出:test
、test/replyer/request
.
鉴于任何路径都是可能的并且没有可用的有效事件列表,我们必须仅检查路径是否是另一个路径的父级。我们可以用正则表达式做到这一点吗?如果是这样,它会是什么样子?有没有更简单/更有效的解决方案?
最佳答案
让 Node 自己完成工作。
const path = require('path');
const relative = path.relative(parent, dir);
return relative && !relative.startsWith('..') && !path.isAbsolute(relative);
它也为你做标准化。
const path = require('path');
const tests = [
['/foo', '/foo'],
['/foo', '/bar'],
['/foo', '/foobar'],
['/foo', '/foo/bar'],
['/foo', '/foo/../bar'],
['/foo', '/foo/./bar'],
['/bar/../foo', '/foo/bar'],
['/foo', './bar'],
['C:\\Foo', 'C:\\Foo\\Bar'],
['C:\\Foo', 'C:\\Bar'],
['C:\\Foo', 'D:\\Foo\\Bar'],
];
tests.forEach(([parent, dir]) => {
const relative = path.relative(parent, dir);
const isSubdir = relative && !relative.startsWith('..') && !path.isAbsolute(relative);
console.log(`[${parent}, ${dir}] => ${isSubdir} (${relative})`);
});
也可以跨驱动器在 Windows 上运行。
[/foo, /foo] => false ()
[/foo, /bar] => false (..\bar)
[/foo, /foobar] => false (..\foobar)
[/foo, /foo/bar] => true (bar)
[/foo, /foo/../bar] => false (..\bar)
[/foo, /foo/./bar] => true (bar)
[/bar/../foo, /foo/bar] => true (bar)
[/foo, ./bar] => false (..\Users\kozhevnikov\Desktop\bar)
[C:\Foo, C:\Foo\Bar] => true (Bar)
[C:\Foo, C:\Bar] => false (..\Bar)
[C:\Foo, D:\Foo\Bar] => false (D:\Foo\Bar)
关于javascript - 确定路径是否是 Node.js 中另一个路径的子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37521893/