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 recursivetrue is given. Syntax:
fs.mkdir(some_location, { recursive: true } )
Bonus:
recursivetrue behaves like force create (i.e. it'll not give EEXIST error). fs.mkdir by default raises this error if the folder already exists.
fs.writeFile overwrites if the file exists, without errors/warning.
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");
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, ifrecursive
true
is given. Syntax:Bonus:
recursive
true
behaves like force create (i.e. it'll not giveEEXIST
error).fs.mkdir
by default raises this error if the folder already exists.fs.writeFile
overwrites if the file exists, without errors/warning.Solution
Use
fs.mkdir
for the folders, and finally usewriteFile
for the file. Example: