首页 > 解决方案 > 在 Node 中查找包含文件名的字符串的目录部分?

问题描述

使用 Node 处理一堆文件,我需要将文件名与目录分开。节点是否有一种简单的方法可以做到这一点而无需额外的依赖?我可以使用像Filename Regex这样的 NPM 包,但我想我会检查是否有现成可用的东西?

例如,假设我们有src/main/css/file.css. 希望这样的事情是可能的:

 const fs = require('fs');
 const path = fs.filePath(String pathAndFileName);  //path = src/main/css
 const file = fs.fileName(String pathAndFileName);  //file = file.css

标签: javascriptnode.js

解决方案


用于操作文件路径的实用程序位于路径模块中。 https://nodejs.org/api/path.html

 const {dirname, basename}  = require('path');

 const path = dirname(String pathAndFileName);
 const file = basename(String pathAndFileName);

推荐阅读