Skip to content

Instantly share code, notes, and snippets.

@ShadowCreator250
Last active July 16, 2020 09:54
Show Gist options
  • Save ShadowCreator250/95b470d6d8e1825a4f0c19d09fd6804c to your computer and use it in GitHub Desktop.
Save ShadowCreator250/95b470d6d8e1825a4f0c19d09fd6804c to your computer and use it in GitHub Desktop.
JS functions to handle paths and files in Node.js
//make directory.  
/* const newDir = (directoryName) => {
        if(path.join(__dirname, directoryName) === true)  {
            console.log(directoryName, ' already exists.'); 
        } else {
        fs.mkdir(path.join(__dirname, directoryName ), {}, err => {
            if(err) throw err; 
                console.log(directoryName, ' created.'); 
        });
    }
};

Credit: Alan ( https://discordapp.com/channels/569209846256369684/569209846256369688/706137779276349513 )

const appendToFile = (folder,file,text) => {
    fs.appendFile(path.join(__dirname, folder, file), `\n${text}` , err => {
        if(err) throw err; 
            console.log(`Appended ${text} to ${file} in ${folder}`);
        });
    };
appendToFile('/testdirectory', 'newFile.txt', 'supaaaaah.'); 

Credit: Alan ( https://discordapp.com/channels/569209846256369684/569209846256369688/706184650288005140 )

const path = require("path"); // built in node path module.
const fs = require("fs"); //built in file system module.


//make directory.
const newDir = (directoryName) => {
    // confirm the folder doesn't exist before continuing.  
  if (path.join(__dirname, directoryName) === true) {
    console.log(`Error: ${directoryName} already exists.`);
  } 
    // if it doesn't exist, create it and confirm it. 
    else {
            fs.mkdir(path.join(__dirname, directoryName), {}, (err) => {
            if (err) throw err;
            console.log(directoryName, " created.");
            });
        }
};

// write to a file.
const writeAFile = (folder, nameForFile, dataToWrite) => {
  fs.writeFile(
    path.join(__dirname, folder, nameForFile),dataToWrite, err => {
      if (err) throw err;
      console.log("testing it out.");
    });
};


// append to a file.
const appendToFile = (folder, file, text) => {
  fs.appendFile(path.join(__dirname, folder, file), `\n${text}`, (err) => {
    if (err) throw err;
    console.log(`Appended ${text} to ${file} in ${folder}`);
  });
};


// read a file.
const readAFile = (folder,file, encoding) => {
    fs.readFile(path.join(__dirname, folder, file), encoding, (err, data) => {
        if(err) throw err; 
            console.log(data); 
    }); 
}

// Rename A file 
const renameFile = (folder, oldName, newName) => {
    fs.rename(path.join(__dirname, folder, oldName), path.join(__dirname, folder, newName), err => {
        if(err) throw err; 
            console.log(`Succes:  ${oldName} renamed to ${newName}.`); 
    }); 
};

renameFile('./jebby', 'jebbysstash.txt', 'alansstash.txt'); 

Credit: Alan ( https://discordapp.com/channels/569209846256369684/569209846256369688/706264589330808832 )

Comments by VirtusGraphics:

path.join(__dirname, directoryName) === true) Path doesn't check if it exist or not, it just works with strings Path just works with paths, not necessarily if it exist or not You can do if(fs.lstatSync(dirname).isDirectory()) { But IDK how well that work with absolute, relative, or sub-dirs You can expand the fs module to have a recursive create dir

Sure Don't know if it all works or not though, but

const path = require("path"); // built in node path module.
const fs = require("fs"); //built in file system module.
//make directory.
const newDir = (directoryName) => {
  // Rely on "else" as little as possible for cleaner flow

  if (fs.lstatSync(directoryName).isdirectory()) return console.log(`Error: ${directoryName} already exists.`);
  
  fs.mkdir(path.join(__dirname, directoryName), err => {
    if (err) throw err;
    console.log("Created folder %s", directoryName);
  });
};
// write to a file.
const writeAFile = (folder, nameForFile, dataToWrite) => {
  // Accept more types of data
  if (typeof(dataToWrite)==="object") JSON.stringify(dataToWrite);
  if (typeof(dataToWrite)!=="string") throw new Error(`Cannot write data of type ${typeof(dataToWrite)}`);

  fs.writeFile(
    path.join(__dirname, folder, nameForFile), dataToWrite, err => {
      if (err) throw err;
      console.log("Data written.");
    });
};
// append to a file.
const appendToFile = (folder, file, dataToWrite) => {
  // Accept more types of data
  if (typeof(dataToWrite)==="object") JSON.stringify(dataToWrite);
  if (typeof(dataToWrite)!=="string") throw new Error(`Cannot write data of type ${typeof(dataToWrite)}`);

  fs.appendFile(path.join(__dirname, folder, file), `\n${dataToWrite}`, err => {
    if (err) throw err;
    console.log(`Appended ${dataToWrite.length} characters to ${file} in ${folder}`);
  });
};
// read a file. Default encoding to utf-8 (which is default anyway)
const readAFile = (folder,file, encoding="utf-8") => {
  fs.readFile(path.join(__dirname, folder, file), encoding, (err, data) => {
      if(err) throw err; 
      console.log(data); 
  }); 
}
// Rename A file 
const renameFile = (folder, oldName, newName) => {
    fs.rename(path.join(__dirname, folder, oldName), path.join(__dirname, folder, newName), err => {
        if(err) throw err; 
        console.log(`Succes:  ${oldName} renamed to ${newName}.`); 
    }); 
};

If you want to check file/folder existence, use fs.lstat for or fs.lstatSync. It returns a Dirent entity, which has methods for checking if it is X thing: thing.isDirectory() thing.isFile() thing.isSocket() thing.isSymbolicLink() And remember that __dirname is relative only to where the file containing this code is. If you require that file and use it, it won't be relative to where you are, but where that utility file you wrote is located Instead you can get the absolute path from where you are using the code with path.resolve("relativePathHere") which returns an absolute path. Pass that in to these utility functions.

Inside it you can have a check to see if it absolute path or relative, using path.isAbsolute(passedPathHere) which returns true or false

( https://discordapp.com/channels/392832386079129630/704005036732055723/706268849976377424 )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment