Skip to content

Instantly share code, notes, and snippets.

@tkihira
Created June 28, 2012 23:28
Show Gist options
  • Save tkihira/3014700 to your computer and use it in GitHub Desktop.
Save tkihira/3014700 to your computer and use it in GitHub Desktop.
mkdir, rmdir and copyDir(deep-copy a directory) in node.js
var mkdir = function(dir) {
// making directory without exception if exists
try {
fs.mkdirSync(dir, 0755);
} catch(e) {
if(e.code != "EEXIST") {
throw e;
}
}
};
var rmdir = function(dir) {
if (path.existsSync(dir)) {
var list = fs.readdirSync(dir);
for(var i = 0; i < list.length; i++) {
var filename = path.join(dir, list[i]);
var stat = fs.statSync(filename);
if(filename == "." || filename == "..") {
// pass these files
} else if(stat.isDirectory()) {
// rmdir recursively
rmdir(filename);
} else {
// rm fiilename
fs.unlinkSync(filename);
}
}
fs.rmdirSync(dir);
} else {
console.warn("warn: " + dir + " not exists");
}
};
var copyDir = function(src, dest) {
mkdir(dest);
var files = fs.readdirSync(src);
for(var i = 0; i < files.length; i++) {
var current = fs.lstatSync(path.join(src, files[i]));
if(current.isDirectory()) {
copyDir(path.join(src, files[i]), path.join(dest, files[i]));
} else if(current.isSymbolicLink()) {
var symlink = fs.readlinkSync(path.join(src, files[i]));
fs.symlinkSync(symlink, path.join(dest, files[i]));
} else {
copy(path.join(src, files[i]), path.join(dest, files[i]));
}
}
};
var copy = function(src, dest) {
var oldFile = fs.createReadStream(src);
var newFile = fs.createWriteStream(dest);
util.pump(oldFile, newFile);
};
@dhananjay-ng
Copy link

thanks!

@metakermit
Copy link

util.pump is deprecated, so as suggested here use:

var copy = function(src, dest) {
	var oldFile = fs.createReadStream(src);
	var newFile = fs.createWriteStream(dest);
	oldFile.pipe(newFile);
};

@danicholls
Copy link

path.existsSync should be fs.existsSync?

@maelfosso
Copy link

It seems not working!
I'm using it in express controller. It ends but no with all directory.

Is there any way to go out from that function with all folder copied?

@nasimmrito
Copy link

nasimmrito commented Nov 28, 2019

Here's a rendition of copy that lets you move a file across partitions:

const move = (source, destination) => {
  let oldFile = fs.createReadStream(source);
  let newFile = fs.createWriteStream(destination);

  oldFile.pipe(newFile);
  oldFile.on('end', function () {
    fs.unlinkSync(source);
  });
}

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