Created
June 28, 2012 23:28
mkdir, rmdir and copyDir(deep-copy a directory) in node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; |
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);
};
path.existsSync
should be fs.existsSync
?
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?
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
thanks!