Explain Codes LogoExplain Codes Logo

Create Directory When Writing To File In Node.js

javascript
file-system
directory-creation
async-await
Anton ShumikhinbyAnton Shumikhin·Dec 7, 2024
TLDR

To create directories while writing to a file in Node.js, employ fs.promises from Node.js's built-in fs module. Use the mkdir function with the {recursive: true} option for the creation of directories and writeFile for writing content. Check out this practical snippet:

const fs = require('fs').promises; async function writeWithDir(filePath, content) { // If life gives you apples, make apple pie 🥧 await fs.mkdir(require('path').dirname(filePath), { recursive: true }); await fs.writeFile(filePath, content); } // Usage writeWithDir('/tmp/a/apple/pie.txt', 'Yummy!') .then(() => console.log('Apple pie is ready!')) .catch(console.error);

This code chunk craftily manages directory structure creation and file writing in one swoop.

Neat synchronous take

If synchronous workflow is your jam, fs.mkdirSync is your solution:

const fs = require('fs'); const path = require('path'); function writeWithDirSync(filePath, content) { const dirPath = path.dirname(filePath); if (!fs.existsSync(dirPath)) { // The path of least resistance is the path of the mkdirSync! fs.mkdirSync(dirPath, { recursive: true }); } fs.writeFileSync(filePath, content); } // Usage writeWithDirSync('/tmp/a/banana/split.txt', 'Yummy!');

No extra packages required! The homemade fs concoction takes charge of your directory checks and creations.

Extra Features With Packages

The native fs methods are great, but some situations call for a little extra. Enter npm packages fs-extra and mkdirp, providing additional filesystem finesse.

Install fs-extra:

npm install --save fs-extra

Use outputFile from fs-extra to automate directory structure and save your file:

const fse = require('fs-extra'); fse.outputFile('/tmp/a/strawberry.txt', 'Sweet!', err => { if (err) { console.error(err); } else { console.log('The fruit salad is ready!'); } });

fs-extra covers everything the fs library does plus some. It's compatible with promises, callbacks, sync, and async/await.

Directory Structure with mkpath

Alternatively, mkpath is a slick maverick that ensures directories are sorted:

Install mkpath:

npm install mkpath

Use mkpath to set up directory structure before file writing:

const mkpath = require('mkpath'); const fs = require('fs'); const directory = '/tmp/a/fruit'; mkpath(directory, function (err) { if (err) { console.error(err); } else { fs.writeFile(`${directory}/salad.txt`, 'Mixed fruits!', (err) => { if (err) throw err; console.log('The fruit salad is still ready!'); }); } });

Error-proofing Async Ops

For robust, error-free I/O, embrace async/await and try/catch blocks:

const fs = require('fs').promises; async function safeWrite(filePath, content) { try { await fs.mkdir(require('path').dirname(filePath), { recursive: true }); // utf8 is the leading lady of character encoding await fs.writeFile(filePath, content, { encoding: 'utf8' }); } catch (err) { console.error("File operation hiccup:", err); } } // Usage safeWrite('/tmp/a/lichee.txt', 'Exotic goodness in writing');

Note our addition of utf8 encoding with fs.writeFile for painless character handling.

Avoiding the NOENT Jump Scare

Beware of the horror flick "ENOENT" error meaning the directory doesn't exist. Squash this bug by setting { recursive: true } in fs.mkdir or fs.mkdirSync so directories are created before writing files.