--- title: Servidor de Node.js sem uma framework slug: Learn/No-servidor/Servidor_node_sem_framework tags: - JavaScript - Nodo - Precisa de Conteúdo - Servidor - sem estrutura translation_of: Learn/Server-side/Node_server_without_framework ---
Este artigo fornece um servidor de ficheiros estático simples com Node.js puro, sem a utilização de uma framework.
NodeJS tem muitas frameworks para ajudá-lo a ter o seu servidor configurado e a funcionar.
Estas não irão corresponder a todas as situações. Um programador pode precisar de criar o seu próprio servidor sem outras dependências.
Um servidor de ficheiros estático simples, criado com Node.js:
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request ', request.url);
var filePath = '.' + request.url;
if (filePath == './') {
filePath = './index.html';
}
var extname = String(path.extname(filePath)).toLowerCase();
var contentType = 'text/html';
var mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.svg': 'application/image/svg+xml'
};
contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');
Estenda este artigo, explicando como é que o código acima funciona. Talvez, uma versão estendida que sirva os ficheiros estáticos e lide com pedidos dinâmicos.