【问题标题】:how to print all sub directory - node.js如何打印所有子目录 - node.js
【发布时间】:2016-05-03 01:00:41
【问题描述】:

再次使用 node.js 进行即时堆栈,需要您的帮助。

我尝试为 cmd 编写脚本,搜索当前目录下的所有子目录(process.cwd), 并仅打印包含用户给我的字符串的字符串(使用 process.argv[2])。

我在这里寻找一些没有成功的答案。 也可以尝试使用 'stat.isDirectory' 和 'fs.readdir',但我仍然需要学习更多方法。

希望有人可以帮助我,

无论如何,谢谢, 埃亚尔

【问题讨论】:

  • 好的,谢谢。但是我如何只打印包含用户给我的字符串的那个?
  • 你为什么不遍历目录名并过滤它......就像var userStr = 'user_provided_string'; getDirectories('.').forEach(function(dirName,i){ if(dirName.indexOf(userStr) > -1){ console.log(dirName); return; } });
  • 这样? jsfiddle.net/eyal4/etfc8unp ,仍然不打印任何东西。也许如果我把所有的子目录放在数组中然后做一个循环?
  • 不是这样,getDirectories 是同步的,你可以在该函数之外调用它。将代码移到getDirectories 函数之外。检查jsfiddle.net/5ycm5uxd/1,但我不确定输出。

标签: javascript node.js frontend subdirectory


【解决方案1】:

我已使用此链接中的getDirectories 函数Get all directories within directory nodejs

在服务器端试试这个代码

var fs = require('fs'),path = require('path');
var userStr = 'user_provided_string'; 

function getDirectories(srcpath) {
  return fs.readdirSync(srcpath).filter(function(file) {
    return fs.statSync(path.join(srcpath, file)).isDirectory();
  });
}

getDirectories('.').forEach(function(dirName,i){
    if(dirName.indexOf(userStr) > -1){ 
       console.log(dirName); 
       return; 
    } 
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 2018-06-28
    • 2019-01-08
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多