Nodejs Quick Tips #1

05/22/2014, Thu
Categories: #JavaScript
Tags: #NodeJs

Creating Multiple Files

Unfortunately, the fs.writeFile does not accept an array for creating a bunch of files at once. To solve this problem, put all files in an array and loop through them to create the files.

// More than One File at Once

var fs = require("fs");

// Use an array to house all files to be created
[
  "thing.txt",
  "thing2.txt",
  "otherFile.txt",
  "abc.txt",
  "def.txt",
  "ghi.txt",
].forEach(function (value) {
  fs.writeFile(value, function (err) {
    if (err) throw err;
  });
});

Get Path of Directory One Up from Current

Using the 'path' variable along with some array operations, the folder one level above the current directory could be found. The value of '1' goes up one level, but this value could be changed to go up many levels as desired.

// One Directory Up

var path = require("path");

// Using this path for example
// /home/williamhuey/Desktop/CodeStuff/
var cwd = process.cwd();

// [ '', 'home', 'williamhuey', 'Desktop', 'CodeStuff']
var pathSep = cwd.split(path.sep);

// [ '', 'home', 'williamhuey', 'Desktop']
var slicedPath = pathSep.slice(0, pathSep.length - 1);

// /home/williamhuey/Desktop/
var oneUpDirectory = slicedPath.join(path.sep);