• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

76
Views
directory is not creating

Am trying to create a directory with subfolders in my application. The new request will create folders only if the parent folder is already there but not creating if root folder is not there.

import { mkdir } from 'fs';

  mkdir(join(__dirname, '../folder_to_create_directory/', req.body.path), (err) => {
        if (err) {
            return "error";
        }
        return "success"
    });

The req.body.path is a path string eg: test/folder/subfolder. The code will work only if we create the "test" folder manually (it is not returning "success" message too even though the directory is being created). IF the test folder is not there then the directory is not creating.

expected output:-

folder_to_create_directory/test/folder/subfolder

almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use fs library to work with a file system.

For nested dirs:

var fs = require('fs');
var dir = join(__dirname, '../folder_to_create_directory/', req.body.path);

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir, { recursive: true });
}

Or, for individual dirs:

var fs = require('fs');
var dir = join(__dirname, '../folder_to_create_directory/', req.body.path);

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}
almost 3 years ago · Juan Pablo Isaza Report

0

you are missing an option "{recursive: true}". Try this example:

const { mkdir } = require("fs");
const {join} = require('path')

const path = join(__dirname, "../folder_to_create_directory", 'test/folder/subfolder')

mkdir(path, { recursive: true }, (err) => {
  if (err) {
    return "error";
  }
  return "success";
});
almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error