如何获得Node.js中目录中所有文件的名称列表?

时间:2023-01-15 09:36:36

I'm trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?

我正在尝试用Node.js获取一个目录中所有文件的名称。我想要输出一个文件名数组。我该怎么做呢?

15 个解决方案

#1


798  

You can use the fs.readdir or fs.readdirSync methods.

你可以使用fs。readdir或fs。readdirSync方法。

fs.readdir

fs.readdir

const testFolder = './tests/';
const fs = require('fs');

fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
})

fs.readdirSync

fs.readdirSync

const testFolder = './tests/';
const fs = require('fs');

fs.readdirSync(testFolder).forEach(file => {
  console.log(file);
})

The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.

这两个方法的不同之处在于,第一个方法是异步的,因此您必须提供一个回调函数,在读取过程结束时执行这个回调函数。

The second is synchronous, it will returns the file name array, but it will stop any further execution of your code until the read process ends.

第二个是同步的,它将返回文件名数组,但是它将停止对代码的任何进一步执行,直到读取过程结束。

#2


161  

The answer above does not perform a recursive search into the directory though. Here's what I did for a recursive search (using node-walk: npm install walk)

上面的答案不会对目录执行递归搜索。下面是我对递归搜索所做的工作(使用节点遍历:npm安装遍历)

var walk    = require('walk');
var files   = [];

// Walker options
var walker  = walk.walk('./test', { followLinks: false });

walker.on('file', function(root, stat, next) {
    // Add this file to the list of files
    files.push(root + '/' + stat.name);
    next();
});

walker.on('end', function() {
    console.log(files);
});

#3


152  

IMO the most convinient way to do such tasks is to use a glob tool. Here's a glob package for node.js. Install with

在我看来,完成这些任务最方便的方法就是使用glob工具。这是node.js的glob包。安装与

npm install glob

Then use wild card to match filenames (example taken from package's website)

然后使用通配符匹配文件名(示例来自package的网站)

var glob = require("glob")

// options is optional
glob("**/*.js", options, function (er, files) {
  // files is an array of filenames.
  // If the `nonull` option is set, and nothing
  // was found, then files is ["**/*.js"]
  // er is an error object or null.
})

#4


73  

Get files in all subdirs

获取所有子目录中的文件

function getFiles (dir, files_){
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files){
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
}

console.log(getFiles('path/to/dir'))

#5


49  

Here's a simple solution using only the native fs and path modules:

这里有一个简单的解决方案,只使用本地的fs和path模块:

// sync version
function walkSync(currentDirPath, callback) {
    var fs = require('fs'),
        path = require('path');
    fs.readdirSync(currentDirPath).forEach(function (name) {
        var filePath = path.join(currentDirPath, name);
        var stat = fs.statSync(filePath);
        if (stat.isFile()) {
            callback(filePath, stat);
        } else if (stat.isDirectory()) {
            walkSync(filePath, callback);
        }
    });
}

or async version (uses fs.readdir instead):

或异步版本(使用fs)。readdir相反):

// async version with basic error handling
function walk(currentDirPath, callback) {
    var fs = require('fs'),
        path = require('path');
    fs.readdir(currentDirPath, function (err, files) {
        if (err) {
            throw new Error(err);
        }
        files.forEach(function (name) {
            var filePath = path.join(currentDirPath, name);
            var stat = fs.statSync(filePath);
            if (stat.isFile()) {
                callback(filePath, stat);
            } else if (stat.isDirectory()) {
                walk(filePath, callback);
            }
        });
    });
}

Then you just call (for sync version):

然后你只需调用(同步版本):

walkSync('path/to/root/dir', function(filePath, stat) {
    // do something with "filePath"...
});

or async version:

或异步版本:

walk('path/to/root/dir', function(filePath, stat) {
    // do something with "filePath"...
});

The difference is in how node blocks while performing the IO. Given that the API above is the same, you could just use the async version to ensure maximum performance.

不同之处在于节点在执行IO时如何阻塞。由于上面的API是相同的,您可以使用异步版本来确保最大的性能。

However there is one advantage to using the synchronous version. It is easier to execute some code as soon as the walk is done, as in the next statement after the walk. With the async version, you would need some extra way of knowing when you are done. Perhaps creating a map of all paths first, then enumerating them. For simple build/util scripts (vs high performance web servers) you could use the sync version without causing any damage.

但是使用同步版本有一个优点。一旦遍历完成,就更容易执行一些代码,如遍历之后的下一个语句中所示。使用异步版本时,您需要一些额外的方法来了解何时完成。可能先创建所有路径的映射,然后枚举它们。对于简单的构建/util脚本(对高性能web服务器),您可以使用同步版本而不会造成任何损害。

#6


16  

Using Promises with ES7

Asynchronous use with mz/fs

The mz module provides promisified versions of the core node library. Using them is simple. First install the library...

mz模块提供了核心节点库的升级版本。使用很简单。第一次安装图书馆…

npm install mz

Then...

然后……

const fs = require('mz/fs');
fs.readdir('./myDir').then(listing => console.log(listing))
  .catch(err => console.error(err));

Alternatively you can write them in asynchronous functions in ES7:

您也可以在ES7中使用异步函数编写它们:

async function myReaddir () {
  try {
    const file = await fs.readdir('./myDir/');
  }
  catch (err) { console.error( err ) }
};

Update for recursive listing

Some of the users have specified a desire to see a recursive listing (though not in the question)... Use fs-promise. It's a thin wrapper around mz.

有些用户指定希望看到递归列表(尽管不是问题)……使用fs-promise。它是mz的一个薄包装。

npm install fs-promise;

then...

然后……

const fs = require('fs-promise');
fs.walk('./myDir').then(
    listing => listing.forEach(file => console.log(file.path))
).catch(err => console.error(err));

#7


12  

Dependencies.

依赖关系。

var fs = require('fs');
var path = require('path');

Definition.

定义。

// String -> [String]
function fileList(dir) {
  return fs.readdirSync(dir).reduce(function(list, file) {
    var name = path.join(dir, file);
    var isDir = fs.statSync(name).isDirectory();
    return list.concat(isDir ? fileList(name) : [name]);
  }, []);
}

Usage.

使用。

var DIR = '/usr/local/bin';

// 1. List all files in DIR
fileList(DIR);
// => ['/usr/local/bin/babel', '/usr/local/bin/bower', ...]

// 2. List all file names in DIR
fileList(DIR).map((file) => file.split(path.sep).slice(-1)[0]);
// => ['babel', 'bower', ...]

Please note that fileList is way too optimistic. For anything serious, add some error handling.

请注意文件列表太乐观了。对于任何严重的问题,添加一些错误处理。

#8


8  

You don't say you want to do it recursively so I assume you only need direct children of the directory.

你不会说你想递归地做它,所以我假设你只需要目录的直接子目录。

Sample code:

示例代码:

const fs = require('fs');
const path = require('path');

fs.readdirSync('your-directory-path')
  .filter((file) => fs.lstatSync(path.join(folder, file)).isFile());

#9


5  

Load fs:

负载fs:

const fs = require('fs');

Read files async:

异步读取文件:

fs.readdir('./dir', function (err, files) {
    // "files" is an Array with files names
});

Read files sync:

读文件同步:

var files = fs.readdirSync('./dir');

#10


4  

Here's an asynchronous recursive version.

这是一个异步递归版本。

    function ( path, callback){
     // the callback gets ( err, files) where files is an array of file names
     if( typeof callback !== 'function' ) return
     var
      result = []
      , files = [ path.replace( /\/\s*$/, '' ) ]
     function traverseFiles (){
      if( files.length ) {
       var name = files.shift()
       fs.stat(name, function( err, stats){
        if( err ){
         if( err.errno == 34 ) traverseFiles()
    // in case there's broken symbolic links or a bad path
    // skip file instead of sending error
         else callback(err)
        }
        else if ( stats.isDirectory() ) fs.readdir( name, function( err, files2 ){
         if( err ) callback(err)
         else {
          files = files2
           .map( function( file ){ return name + '/' + file } )
           .concat( files )
          traverseFiles()
         }
        })
        else{
         result.push(name)
         traverseFiles()
        }
       })
      }
      else callback( null, result )
     }
     traverseFiles()
    }

#11


3  

Took the general approach of @Hunan-Rostomyan, made it a litle more concise and added excludeDirs argument. It'd be trivial to extend with includeDirs, just follow same pattern:

采用了@Hunan-Rostomyan的一般方法,使其更简洁,并增加了排他性论点。用include扩展是很简单的,只要遵循相同的模式:

import * as fs from 'fs';
import * as path from 'path';

function fileList(dir, excludeDirs?) {
    return fs.readdirSync(dir).reduce(function (list, file) {
        const name = path.join(dir, file);
        if (fs.statSync(name).isDirectory()) {
            if (excludeDirs && excludeDirs.length) {
                excludeDirs = excludeDirs.map(d => path.normalize(d));
                const idx = name.indexOf(path.sep);
                const directory = name.slice(0, idx === -1 ? name.length : idx);
                if (excludeDirs.indexOf(directory) !== -1)
                    return list;
            }
            return list.concat(fileList(name, excludeDirs));
        }
        return list.concat([name]);
    }, []);
}

Example usage:

使用示例:

console.log(fileList('.', ['node_modules', 'typings', 'bower_components']));

#12


1  

Get sorted filenames. You can filter results based on a specific extension such as '.txt', '.jpg' and so on.

文件名排序。您可以基于特定的扩展(如')过滤结果。txt', '。jpg'等等。

import * as fs from 'fs';
import * as Path from 'path';

function getFilenames(path, extension) {
    return fs
        .readdirSync(path)
        .filter(
            item =>
                fs.statSync(Path.join(path, item)).isFile() &&
                (extension === undefined || Path.extname(item) === extension)
        )
        .sort();
}

#13


0  

Just a heads up: if you're planning to perform operations on each file in a directory, try vinyl-fs (which is used by gulp, the streaming build system).

请注意:如果您打算对目录中的每个文件执行操作,请尝试使用vinyl-fs(由流构建系统gulp使用)。

#14


0  

I made a node module to automate this task: mddir

我制作了一个节点模块来自动化这个任务:mddir

Usage

node mddir "../relative/path/"

节点mddir“相对路径/ . . /”

To install: npm install mddir -g

安装:npm安装mddir -g

To generate markdown for current directory: mddir

为当前目录:mddir生成markdown

To generate for any absolute path: mddir /absolute/path

生成任何绝对路径:mddir /绝对路径

To generate for a relative path: mddir ~/Documents/whatever.

生成相对路径:mddir ~/Documents/随便什么。

The md file gets generated in your working directory.

md文件在您的工作目录中生成。

Currently ignores node_modules, and .git folders.

当前忽略node_modules和.git文件夹。

Troubleshooting

If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.

如果您收到错误的“node\r: No such file or directory”,那么问题是您的操作系统使用不同的行结尾,如果不显式地将行结尾样式设置为Unix, mddir就无法解析它们。这通常会影响Windows,但也会影响Linux的一些版本。必须在mddir npm全局bin文件夹中执行将行结束设置为Unix样式的操作。

Line endings fix

Get npm bin folder path with:

获取npm bin文件夹路径:

npm config get prefix

npm配置得到前缀

Cd into that folder

Cd到那个文件夹

brew install dos2unix

酿造安装dos2unix

dos2unix lib/node_modules/mddir/src/mddir.js

dos2unix lib / node_modules / mddir / src / mddir.js

This converts line endings to Unix instead of Dos

这将行结束符转换为Unix而不是Dos

Then run as normal with: node mddir "../relative/path/".

然后按常规运行:node mddir ". /relative/path/"。

Example generated markdown file structure 'directoryList.md'

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js

#15


-1  

function getFilesRecursiveSync(dir, fileList, optionalFilterFunction) {
    if (!fileList) {
        grunt.log.error("Variable 'fileList' is undefined or NULL.");
        return;
    }
    var files = fs.readdirSync(dir);
    for (var i in files) {
        if (!files.hasOwnProperty(i)) continue;
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()) {
            getFilesRecursiveSync(name, fileList, optionalFilterFunction);
        } else {
            if (optionalFilterFunction && optionalFilterFunction(name) !== true)
                continue;
            fileList.push(name);
        }
    }
}

#1


798  

You can use the fs.readdir or fs.readdirSync methods.

你可以使用fs。readdir或fs。readdirSync方法。

fs.readdir

fs.readdir

const testFolder = './tests/';
const fs = require('fs');

fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
})

fs.readdirSync

fs.readdirSync

const testFolder = './tests/';
const fs = require('fs');

fs.readdirSync(testFolder).forEach(file => {
  console.log(file);
})

The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.

这两个方法的不同之处在于,第一个方法是异步的,因此您必须提供一个回调函数,在读取过程结束时执行这个回调函数。

The second is synchronous, it will returns the file name array, but it will stop any further execution of your code until the read process ends.

第二个是同步的,它将返回文件名数组,但是它将停止对代码的任何进一步执行,直到读取过程结束。

#2


161  

The answer above does not perform a recursive search into the directory though. Here's what I did for a recursive search (using node-walk: npm install walk)

上面的答案不会对目录执行递归搜索。下面是我对递归搜索所做的工作(使用节点遍历:npm安装遍历)

var walk    = require('walk');
var files   = [];

// Walker options
var walker  = walk.walk('./test', { followLinks: false });

walker.on('file', function(root, stat, next) {
    // Add this file to the list of files
    files.push(root + '/' + stat.name);
    next();
});

walker.on('end', function() {
    console.log(files);
});

#3


152  

IMO the most convinient way to do such tasks is to use a glob tool. Here's a glob package for node.js. Install with

在我看来,完成这些任务最方便的方法就是使用glob工具。这是node.js的glob包。安装与

npm install glob

Then use wild card to match filenames (example taken from package's website)

然后使用通配符匹配文件名(示例来自package的网站)

var glob = require("glob")

// options is optional
glob("**/*.js", options, function (er, files) {
  // files is an array of filenames.
  // If the `nonull` option is set, and nothing
  // was found, then files is ["**/*.js"]
  // er is an error object or null.
})

#4


73  

Get files in all subdirs

获取所有子目录中的文件

function getFiles (dir, files_){
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files){
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
}

console.log(getFiles('path/to/dir'))

#5


49  

Here's a simple solution using only the native fs and path modules:

这里有一个简单的解决方案,只使用本地的fs和path模块:

// sync version
function walkSync(currentDirPath, callback) {
    var fs = require('fs'),
        path = require('path');
    fs.readdirSync(currentDirPath).forEach(function (name) {
        var filePath = path.join(currentDirPath, name);
        var stat = fs.statSync(filePath);
        if (stat.isFile()) {
            callback(filePath, stat);
        } else if (stat.isDirectory()) {
            walkSync(filePath, callback);
        }
    });
}

or async version (uses fs.readdir instead):

或异步版本(使用fs)。readdir相反):

// async version with basic error handling
function walk(currentDirPath, callback) {
    var fs = require('fs'),
        path = require('path');
    fs.readdir(currentDirPath, function (err, files) {
        if (err) {
            throw new Error(err);
        }
        files.forEach(function (name) {
            var filePath = path.join(currentDirPath, name);
            var stat = fs.statSync(filePath);
            if (stat.isFile()) {
                callback(filePath, stat);
            } else if (stat.isDirectory()) {
                walk(filePath, callback);
            }
        });
    });
}

Then you just call (for sync version):

然后你只需调用(同步版本):

walkSync('path/to/root/dir', function(filePath, stat) {
    // do something with "filePath"...
});

or async version:

或异步版本:

walk('path/to/root/dir', function(filePath, stat) {
    // do something with "filePath"...
});

The difference is in how node blocks while performing the IO. Given that the API above is the same, you could just use the async version to ensure maximum performance.

不同之处在于节点在执行IO时如何阻塞。由于上面的API是相同的,您可以使用异步版本来确保最大的性能。

However there is one advantage to using the synchronous version. It is easier to execute some code as soon as the walk is done, as in the next statement after the walk. With the async version, you would need some extra way of knowing when you are done. Perhaps creating a map of all paths first, then enumerating them. For simple build/util scripts (vs high performance web servers) you could use the sync version without causing any damage.

但是使用同步版本有一个优点。一旦遍历完成,就更容易执行一些代码,如遍历之后的下一个语句中所示。使用异步版本时,您需要一些额外的方法来了解何时完成。可能先创建所有路径的映射,然后枚举它们。对于简单的构建/util脚本(对高性能web服务器),您可以使用同步版本而不会造成任何损害。

#6


16  

Using Promises with ES7

Asynchronous use with mz/fs

The mz module provides promisified versions of the core node library. Using them is simple. First install the library...

mz模块提供了核心节点库的升级版本。使用很简单。第一次安装图书馆…

npm install mz

Then...

然后……

const fs = require('mz/fs');
fs.readdir('./myDir').then(listing => console.log(listing))
  .catch(err => console.error(err));

Alternatively you can write them in asynchronous functions in ES7:

您也可以在ES7中使用异步函数编写它们:

async function myReaddir () {
  try {
    const file = await fs.readdir('./myDir/');
  }
  catch (err) { console.error( err ) }
};

Update for recursive listing

Some of the users have specified a desire to see a recursive listing (though not in the question)... Use fs-promise. It's a thin wrapper around mz.

有些用户指定希望看到递归列表(尽管不是问题)……使用fs-promise。它是mz的一个薄包装。

npm install fs-promise;

then...

然后……

const fs = require('fs-promise');
fs.walk('./myDir').then(
    listing => listing.forEach(file => console.log(file.path))
).catch(err => console.error(err));

#7


12  

Dependencies.

依赖关系。

var fs = require('fs');
var path = require('path');

Definition.

定义。

// String -> [String]
function fileList(dir) {
  return fs.readdirSync(dir).reduce(function(list, file) {
    var name = path.join(dir, file);
    var isDir = fs.statSync(name).isDirectory();
    return list.concat(isDir ? fileList(name) : [name]);
  }, []);
}

Usage.

使用。

var DIR = '/usr/local/bin';

// 1. List all files in DIR
fileList(DIR);
// => ['/usr/local/bin/babel', '/usr/local/bin/bower', ...]

// 2. List all file names in DIR
fileList(DIR).map((file) => file.split(path.sep).slice(-1)[0]);
// => ['babel', 'bower', ...]

Please note that fileList is way too optimistic. For anything serious, add some error handling.

请注意文件列表太乐观了。对于任何严重的问题,添加一些错误处理。

#8


8  

You don't say you want to do it recursively so I assume you only need direct children of the directory.

你不会说你想递归地做它,所以我假设你只需要目录的直接子目录。

Sample code:

示例代码:

const fs = require('fs');
const path = require('path');

fs.readdirSync('your-directory-path')
  .filter((file) => fs.lstatSync(path.join(folder, file)).isFile());

#9


5  

Load fs:

负载fs:

const fs = require('fs');

Read files async:

异步读取文件:

fs.readdir('./dir', function (err, files) {
    // "files" is an Array with files names
});

Read files sync:

读文件同步:

var files = fs.readdirSync('./dir');

#10


4  

Here's an asynchronous recursive version.

这是一个异步递归版本。

    function ( path, callback){
     // the callback gets ( err, files) where files is an array of file names
     if( typeof callback !== 'function' ) return
     var
      result = []
      , files = [ path.replace( /\/\s*$/, '' ) ]
     function traverseFiles (){
      if( files.length ) {
       var name = files.shift()
       fs.stat(name, function( err, stats){
        if( err ){
         if( err.errno == 34 ) traverseFiles()
    // in case there's broken symbolic links or a bad path
    // skip file instead of sending error
         else callback(err)
        }
        else if ( stats.isDirectory() ) fs.readdir( name, function( err, files2 ){
         if( err ) callback(err)
         else {
          files = files2
           .map( function( file ){ return name + '/' + file } )
           .concat( files )
          traverseFiles()
         }
        })
        else{
         result.push(name)
         traverseFiles()
        }
       })
      }
      else callback( null, result )
     }
     traverseFiles()
    }

#11


3  

Took the general approach of @Hunan-Rostomyan, made it a litle more concise and added excludeDirs argument. It'd be trivial to extend with includeDirs, just follow same pattern:

采用了@Hunan-Rostomyan的一般方法,使其更简洁,并增加了排他性论点。用include扩展是很简单的,只要遵循相同的模式:

import * as fs from 'fs';
import * as path from 'path';

function fileList(dir, excludeDirs?) {
    return fs.readdirSync(dir).reduce(function (list, file) {
        const name = path.join(dir, file);
        if (fs.statSync(name).isDirectory()) {
            if (excludeDirs && excludeDirs.length) {
                excludeDirs = excludeDirs.map(d => path.normalize(d));
                const idx = name.indexOf(path.sep);
                const directory = name.slice(0, idx === -1 ? name.length : idx);
                if (excludeDirs.indexOf(directory) !== -1)
                    return list;
            }
            return list.concat(fileList(name, excludeDirs));
        }
        return list.concat([name]);
    }, []);
}

Example usage:

使用示例:

console.log(fileList('.', ['node_modules', 'typings', 'bower_components']));

#12


1  

Get sorted filenames. You can filter results based on a specific extension such as '.txt', '.jpg' and so on.

文件名排序。您可以基于特定的扩展(如')过滤结果。txt', '。jpg'等等。

import * as fs from 'fs';
import * as Path from 'path';

function getFilenames(path, extension) {
    return fs
        .readdirSync(path)
        .filter(
            item =>
                fs.statSync(Path.join(path, item)).isFile() &&
                (extension === undefined || Path.extname(item) === extension)
        )
        .sort();
}

#13


0  

Just a heads up: if you're planning to perform operations on each file in a directory, try vinyl-fs (which is used by gulp, the streaming build system).

请注意:如果您打算对目录中的每个文件执行操作,请尝试使用vinyl-fs(由流构建系统gulp使用)。

#14


0  

I made a node module to automate this task: mddir

我制作了一个节点模块来自动化这个任务:mddir

Usage

node mddir "../relative/path/"

节点mddir“相对路径/ . . /”

To install: npm install mddir -g

安装:npm安装mddir -g

To generate markdown for current directory: mddir

为当前目录:mddir生成markdown

To generate for any absolute path: mddir /absolute/path

生成任何绝对路径:mddir /绝对路径

To generate for a relative path: mddir ~/Documents/whatever.

生成相对路径:mddir ~/Documents/随便什么。

The md file gets generated in your working directory.

md文件在您的工作目录中生成。

Currently ignores node_modules, and .git folders.

当前忽略node_modules和.git文件夹。

Troubleshooting

If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.

如果您收到错误的“node\r: No such file or directory”,那么问题是您的操作系统使用不同的行结尾,如果不显式地将行结尾样式设置为Unix, mddir就无法解析它们。这通常会影响Windows,但也会影响Linux的一些版本。必须在mddir npm全局bin文件夹中执行将行结束设置为Unix样式的操作。

Line endings fix

Get npm bin folder path with:

获取npm bin文件夹路径:

npm config get prefix

npm配置得到前缀

Cd into that folder

Cd到那个文件夹

brew install dos2unix

酿造安装dos2unix

dos2unix lib/node_modules/mddir/src/mddir.js

dos2unix lib / node_modules / mddir / src / mddir.js

This converts line endings to Unix instead of Dos

这将行结束符转换为Unix而不是Dos

Then run as normal with: node mddir "../relative/path/".

然后按常规运行:node mddir ". /relative/path/"。

Example generated markdown file structure 'directoryList.md'

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js

#15


-1  

function getFilesRecursiveSync(dir, fileList, optionalFilterFunction) {
    if (!fileList) {
        grunt.log.error("Variable 'fileList' is undefined or NULL.");
        return;
    }
    var files = fs.readdirSync(dir);
    for (var i in files) {
        if (!files.hasOwnProperty(i)) continue;
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()) {
            getFilesRecursiveSync(name, fileList, optionalFilterFunction);
        } else {
            if (optionalFilterFunction && optionalFilterFunction(name) !== true)
                continue;
            fileList.push(name);
        }
    }
}