How do you get a list of the names of all files present in a directory in Node.js?

后端 未结 25 1281
天涯浪人
天涯浪人 2020-11-22 07:47

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?

25条回答
  •  逝去的感伤
    2020-11-22 08:17

    I made a node module to automate this task: mddir

    Usage

    node mddir "../relative/path/"

    To install: npm install mddir -g

    To generate markdown for current directory: mddir

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

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

    The md file gets generated in your working directory.

    Currently ignores node_modules, and .git folders.

    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.

    Line endings fix

    Get npm bin folder path with:

    npm config get prefix

    Cd into that folder

    brew install dos2unix

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

    This converts line endings to Unix instead of Dos

    Then run as normal with: 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
    

提交回复
热议问题