sanjar-notes / nodejs

Node, Express and helper app libs
https://sanjar-notes.github.io/nodejs/
GNU General Public License v3.0
0 stars 0 forks source link

Create a file at location, with all intermediate folders (if they don't exist) #3

Open sanjarcode opened 1 year ago

sanjarcode commented 1 year ago

Problem

Create a file at given location, with all intermediate folders (if they don't exist), The fs.writeFile function cannot do this, it expects all folders to exist.

Catch

fs.mkdir can make all the folders, if recursive true is given. Syntax:

fs.mkdir(some_location, { recursive: true } )

Bonus:

Solution

Use fs.mkdir for the folders, and finally use writeFile for the file. Example:

const fs = require('fs/promises');
const path = require('path');

const pathToFile = 'some-path-here';

await fs.mkdir(path.dirname(pathToFile), { recursive: true }); // because `mkdir` needs path to folder, not a file
await fs.writeFile(pathToFile, "whatever");
sanjarcode commented 1 year ago

task: Add to notes