Mots-clé : serveur http

NodeJS qui sert des fichiers et accède à MongoDB

// Exemple copié collé et adapté sur stackoverflow :
// http://stackoverflow.com/questions/15630770/node-js-check-if-path-is-file-or-directory
// http://stackoverflow.com/questions/7268033/basic-static-file-server-in-nodejs
//
var http = require('http'),
    url = require('url'),
    fs = require('fs'),
    mongoose = require('mongoose'),
    fileSystem = require('fs'),
    path = require('path');
var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",
    "js": "text/javascript",
    "css": "text/css"};

var server;
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;

var personneSchema = new Schema({
  nom: String,
  prenom: String
});
var Personne = db.model('Personne', personneSchema);

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('DB connexion reussie');
    server = http.createServer(function (request, response) {
        if (request.url=='/personnes') {
            console.log("> JSON");
            Personne.find({}).select('nom prenom').exec(function (err, p) {
                if (err) {
                    return console.log(err);
                }
                var retour='[';
                for (var i = 0; i < p.length; i++) {
                    retour+='{'+ p[i].nom+', '+p[i].prenom+'},';
                };
                retour=retour.substr(0, retour.length-2)+']';
                response.writeHead(200, {
                    'Cache-Control': 'no-cache, must-revalidate',
                    'Expires': 'Mon, 26 Jul 1997 05:00:00 GMT',
                    'Content-type': 'application/json'
                });
                response.end(retour);
            });
            // Stopper tout traitement :
            return;
        }
        var uri = url.parse(request.url).pathname;
        var filename = path.join(process.cwd(), uri);
        console.log("> " + filename);
        fs.exists(filename, function(exists) {
            if ((!exists) || (fs.lstatSync(filename).isDirectory())) {
                console.log(">> fichier inexistant : " + filename);
                response.writeHead(200, {'Content-Type': 'text/plain'});
                response.write('404 Not Found\n');
                response.end();
                // Stopper tout traitement :
                return;
            }
            var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
            response.writeHead(200, {'Content-Type':mimeType});

            var fileStream = fs.createReadStream(filename);
            fileStream.pipe(response);
        });

        //var p = new Personne({
        // nom: 'Pons',
        // prenom: 'Olivier'
        //});
        //p.save(function (err) {
        // if (err) {
        // return console.log(err);
        // }
        // var query = Personne.find();
        // query.select('nom prenom');
        // query.exec(function (err, p) {
        // if (err) return console.log(err);
        // for (var i = 0; i < p.length; i++) {
        // console.log(p[i].nom+' '+p[i].prenom);
        // };
        // console.log('Nombre total d\'enregistrements : '+p.length);
        // });
        //})
    });
    // Listen on port 8000, IP defaults to 127.0.0.1
    server.listen(8000);
    // Put a friendly message on the terminal
    console.log("Server running at http://127.0.0.1:8000/");
});