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).
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())]);