Skip to content

Instantly share code, notes, and snippets.

@jacksonfdam
Last active December 17, 2016 16:30
Show Gist options
  • Save jacksonfdam/4d81c4c0b2eddc519fbedc0f70188c2b to your computer and use it in GitHub Desktop.
Save jacksonfdam/4d81c4c0b2eddc519fbedc0f70188c2b to your computer and use it in GitHub Desktop.
FileSystem no NodeJS
var fs = require('fs');
fs.stat('data.txt', function (err, stats) {
if (err)
throw err;
if (stats.isFile()) {
console.log('É um arquivo!');
}
if (stats.isDirectory()) {
console.log('É um diretório!');
}
for (var i in stats) {
if ('function' !== typeof stats[i])
console.log(i + '\t= ' + stats[i]);
}
});
fs.rename('data2.txt', 'data2_new.txt', function (err) {
if (err)
throw err;
console.log('Renomeado');
});
fs.chmod('data3.txt', '0777', function (err) {
if (err)
throw err;
console.log('Mudou as permissoes');
});
var fs = require('fs');
fs.readFile('/index.html', function(erro, arquivo){
if (erro) throw erro;
console.log(arquivo);
});
var arquivo = fs.readFileSync('/index.html');
console.log(arquivo);
fs.readFile("data.txt", "utf8", function(error, data) {
console.log(data);
});
var data = fs.readFileSync("foo.txt", "utf8");
console.log(data);
fs.watch(__dirname + '/index.html', function(curr, prev) {
fs.readFile(__dirname + '/index.html', "utf-8", function(err, data) {
if (err) throw err;
console.log(data);
});
});
fs.watch(__dirname + '/index.html', {persistent: true}, function(event, filename) {
console.log(event + " event occurred on " + filename);
});
//GRAVAR ARQUIVO
var fs = require('fs');
fs.writeFile('data2.txt', 'Hello, World!', function (err) {
if (err)
throw err;
});
//Excluir Arquivo
fs.unlink('data.txt', function(err) {
if (err) {
return console.error(err);
}
console.log("Apagado com sucesso");
});
//LER PASTA
var fs = require('fs');
fs.readdir('.', function (err, files) {
if (err)
throw err;
for (var index in files) {
console.log(files[index]);
}
});
fs.mkdir('/pasta2',function(err){
if (err) {
return console.error(err);
}
console.log("Sucesso!");
});
fs.readdir("/pasta2/",function(err, files){
if (err) {
return console.error(err);
}
files.forEach( function (file){
console.log( file );
});
});
var fs = require('fs');
var traverseFileSystem = function (currentPath) {
console.log(currentPath);
var files = fs.readdirSync(currentPath);
for (var i in files) {
var currentFile = currentPath + '/' + files[i];
var stats = fs.statSync(currentFile);
if (stats.isFile()) {
console.log(currentFile);
}
else if (stats.isDirectory()) {
traverseFileSystem(currentFile);
}
}
};
traverseFileSystem('..');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment