Socket
Socket
Sign inDemoInstall

@danmasta/walk

Package Overview
Dependencies
7
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @danmasta/walk

Directory and file walking utility for node apps


Version published
Weekly downloads
16
increased by77.78%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

Walk

Directory and file walking utility for node apps

Features:

  • Easy to use
  • Simple, lightweight, and fast
  • Async, sync, streams, and promise api
  • Simple filtering with glob pattern matching
  • Require or import file contents, or read as stream, buffer, or string
  • Resolves require-style path strings
  • Normalized file objects with helper methods
  • Fast pattern matching via micromatch
  • Include and exclude pattern matching options
  • Only 2 dependencies: micromatch, lodash

About

I needed a better way to walk directories and read files during build and/or run time. I wanted an api that was simple, supported glob pattern matching like gulp, and returned objects with a similar format as vinyl. This package allows you to simply read any directory (or file), filter results with glob pattern matching, and return an array of file objects. It can also require or import file contents, read them as streams, buffers, or strings, and resolve require-style path strings.

Usage

Add walk as a dependency for your app and install via npm

npm install @danmasta/walk --save

Require the package in your app

const walk = require('@danmasta/walk');

By default walk returns a readable stream interface. You can use the methods: map(), tap(), each(), promise(), then(), and catch() to iterate file objects and return promises

Options

nametypedescription
cwdstringBase directory to start walk from. Default is process.cwd
rootstringDirectory or file path as root to walk from. This affects the relative paths used in file objects and matching. Default is ./
srcarray|string|regexpMicromatch pattern for result filtering by including any matches. Can be a path string, glob pattern string, regular expression, or an array of strings. Defaults to *(../)*(**/)*
dotbooleanWhether or not to include dot files when matching. Default is true
ignorearray|string|regexpMicromatch pattern for result filtering by ignoring any matches. Can be a path string, glob pattern string, regular expression, or an array of strings. Defaults to *(../)*(**/)(.git|node_modules)
encodingstringWhich encoding to use when reading or writing file contents. Default is utf8
resolvebooleanWhether or not to attempt to resolve file paths if not found. Default is true
pathsarray|stringWhich paths to walk for files. Default is undefined

Methods

NameDescription
map(fn)Runs an iterator function over each file. Returns a promise that resolves with a new array of return values
tap(fn)Runs an iterator function over each file. Returns a promise that resolves with an array of file objects
each(fn)Runs an iterator function over each file. Returns a promise that resolves with undefined
promiseReturns a promise that resolves with an array of file objects
then(fn)Run a callback when the promise is fulfilled. Returns a promise that resolves with an array of file objects
catch(fn)Run a callback when the promise is rejected. Returns a promise that resolves with an array of file objects

File Objects

Each file object returned from walk has the following signature:

Properties
nametypedescription
cwdstringCurrent working directory. Defaults to process.cwd
rootstringBase directory to use for relative pathing. Defaults to cwd
pathstringAbsolute path of the file on disk
relativestringRelative path of file based from normalized root
relativeFromCwdstringRelative path of file based from normalized cwd
dirstringParent directory where file is located
basestringFile name with extension
namestringFile name without extension
extstringFile extension
statobjectThe fs.stat object for the file
contentsstring|objectContents of the file. Default is undefined
encodingstringDefault encoding to use when reading or writing file contents. Default is utf8
Methods
namedescription
createReadStream(opts)Returns a readable stream for the file
createWriteStream(opts)Returns a writable stream for the file
append(data, opts)Appends data to the file
read(opts)Reads the file contents. Returns string or buffer based on encoding
readAsString(opts)Shortcut for read() that ensures encoding is set or throws an error
readAsBuffer(opts)Shortcut for read() that sets the encoding to null
readStrAlias for readAsString
readBufAlias for readAsBuffer
write(data, opts)Writes data to the file
requireReads the file contents using require
importReads the file contents using import. Returns a promise
requireOrImportReads the file contents using import or require based on esm-ness. Returns a promise
requireImportOrReadReads the file contents using import or require if able, otherwise reads as string or buffer based on encoding. Returns a promise
isModuleReturns true if file.contents is a module
isBufferReturns true if file.contents is a buffer
isStreamReturns true if file.contents is a stream
isNullReturns true if file.contents is null
isNilReturns true if file.contents is null or undefined
isStringReturns true if file.contents is a string
isDirectoryReturns true if the file is a directory
isSymbolicLinkReturns true if the file is a symbolic link
isBlockDeviceReturns true if the file is a block device
isCharacterDeviceReturns true if the file is a character device
isFIFOReturns true if the file is a first-in-first-out (FIFO) pipe
isFileReturns true if the file is a file
isSocketReturns true if the file is a socket
isEmptyReturns true if the file is empty (zero bytes)
getEncodingFromBomReturns the encoding from the file byte order mark if set, otherwise undefined

Sync

This package also supports a fully synchronous api. Instead of requiring the default package just require @danmasta/walk/sync. The api is exactly the same for walking and file objects

Examples

const walk = require('@danmasta/walk');

Walk the current working directory and pipe all files to a destination stream

walk('./').pipe(writeStream());

Walk the current working directory, exclude all .json files

walk('./', { src: '**/*.!(json)' }).then(res => {
    console.log('files:', res);
});

Walk a child directory, include only .json files

walk('./config', { src: '**/*.json' }).then(res => {
    console.log('files:', res);
});

Walk a directory using an absolute path

walk('/usr/local').then(res => {
    console.log('files:', res);
});

Read the contents of all pug files in ./views as a string

walk('./views', { src: '**/*.pug' }).map(file => {
    file.readStr().then(res => {
        console.log('template:', file.path, res);
    });
});

Read the contents of all pug files in ./views as a buffer

walk('./views', { src: '**/*.pug' }).map(file => {
    file.readBuf().then(res => {
        console.log('template:', file.path, res);
    });
});

Require all js files in the ./routes directory and run a callback for each one

walk('./routes', { src: '**/*.js' }).each(route => {
    app.use(route.require());
}).then(() => {
    console.log('all routes loaded');
});

Load all templates from the ./views directory synchronously

const walk = require('@danmasta/walk/sync');

let templates = walk('./views', { src: '**/*.pug' });

console.log('templates:', templates);

Testing

Tests are currently run using mocha and chai. To execute tests run npm run test. To generate unit test coverage reports run npm run coverage

Contact

If you have any questions feel free to get in touch

Keywords

FAQs

Last updated on 02 May 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc