-
-
Save edinsoncs/18ad28bdec9efebbd295 to your computer and use it in GitHub Desktop.
fs, url, http, nodejs
This file contains hidden or 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 http = require('http'); | |
var url = require('url'); | |
var port = 3000; | |
var fs = require('fs'); | |
var path = require('path'); | |
var mimes = { | |
'.html': 'text/html', | |
'.css': 'text/css', | |
'.js': 'text/javascript', | |
'.gif': 'image/gif', | |
'.jpg': 'image/jpeg', | |
'.png': 'image/png' | |
} | |
function fileAccess(filePath){ | |
return new Promise(function(resolve, reject){ | |
fs.access(filepath, fs.F_OK, function(err){ | |
if(!err){ | |
resolve(filePath); | |
} | |
else { | |
reject(error); | |
} | |
}); | |
}); | |
} | |
function fileReader(filePath) { | |
return new Promise(function(resolve, reject){ | |
fs.readFile(filePath, function(err, content){ | |
if(!err){ | |
resolve(content) | |
} | |
else { | |
reject(err); | |
} | |
}); | |
}); | |
} | |
function creaciondelServer(req, res){ | |
console.log(url); | |
var baseURI = url.parse(req.url); | |
var filePath = __dirname + (baseURI.pathname === '/' ? '/index.html' : baseURI.pathname); | |
fileAccess(filePath).then(fileReader).then(function content(){ | |
res.writeHead(200, {'Content-type': contentType}); | |
res.end(content, 'utf-8'); | |
}) | |
.catch(function err(){ | |
res.writeHead(500); | |
res.end(JSON.stringify(err)); | |
}); | |
console.log(filePath); | |
console.log('soy pathname ' + JSON.stringify(baseURI)); | |
//dirname nos brinda la url de nuestro directory | |
console.log('__dirname: ' + __dirname); | |
//process.cdw() functio nos brinda la url de nuestro directory | |
console.log('process.cwd() ' + process.cwd()); | |
} | |
http.createServer(creaciondelServer).listen(port, function(){ | |
console.log('corriendo server ' + port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment