DEV Community

Cover image for Access file system like object
Rafi
Rafi

Posted on

4 2

Access file system like object

When you write small scripts in nodejs it is sometimes annoying to deal with the file system API. Wouldn't it be nice if you can access files and folders like you access any object and traverse them easily like you traverse an object in memory.

I came up really simple js proxy wrapper around the file system API so that allows you to treat as if it is an object.

you can install it using npm first

$ npm i node_file_object
Enter fullscreen mode Exit fullscreen mode

and then use it as follows

const createFileObject = require("node_file_object");

// Path is optional if it is not speficied '/' will be used
// path supplied here should be a folder path
const fileObject = createFileObject({ path: "/home/username" });

// List all files and folders in directory as strings
console.log(Object.keys(fileObject));

// List all files and folders as array of objects with additional attributes
console.log(fileObject.getChildren());

// READ the content of a given file
console.log(fileObject[".zshrc"].getContent());

// Walk through file system like you do on an object
// /home/username/Documents/notes.md
const documents = fileObject["Documents"];
console.log(documents["notes.md"].getContent());
Enter fullscreen mode Exit fullscreen mode

Like everything in life this comes with its own downsides. Since it is meant to function like direct object access it uses synchronous file API's which might cause performance issues when used in large projects (since it has to wait for IO to complete). But this will prove useful for smaller scripts where this does not matter.

Here is the source PR's are welcomed!!

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay