Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a runtime directory in Node.js

I’m working on a service which handles file uploads to a server. In my service (Node.js) I want to create a certain file structure, put it in a directory, convert it to a blob and then upload it.

I am of course aware of the Node file system (fs), but as far as I know it writes files/directories to disk. I have no interest in saving the directories, I just want to keep a directory in runtime to which I can add some files (also runtime) before converting it to a blob.

I also know about fs.mkdtempSync, which you could use in this way. I don’t want it to stay on disk however, in case something throws when trying to delete the temporary directory (see the finally block).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Do you know if there is any such functionality in Node.js? If not, is there any npm package which could help me achieve this?

>Solution :

You can use the npm package called memfs and use it like this

const { Volume } = require('memfs');
const fs = Volume.fromJSON({});

fs.mkdirSync('/mydir');
fs.writeFileSync('/mydir/myfile.txt', 'Hello world!');

// ... manipulate the in-memory file system as needed ...

// Convert the directory to a blob
const directoryBlob = new Blob([JSON.stringify(fs.toJSON())]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading