Nodejs Quick Tips #1

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
1
2
3
4
5
6
7
8
9
10
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 as many level as desired.

One Directory Up
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);