var http = require("http")
var path = require("path")
var express = require("express")
c'est un middleware qui permet de logger le requet dans la console
tu n'es pas obliger de tout réinventer
surtout n'oublie pas de faire un
npm install morgan body-parser
var logger = require("morgan")
var bodyParser = require("body-parser") // ça permet de parser la requet
var app = express()
J'utiliser mongoose à la place de mongodb
mongoose ofre plusieur avantage que mongodb
dans le sens ou a connection est faite au debut et on peut utiliser le model partout ou l'on veu
Visite le site de mongoose pour la documentation (mongoosejs.com/docs/api.html)
var mongoose = require("mongoose")
Je définit le Schéma qui n'est tout autre que la structure de mes document qui sont dans la base de donnée
var UserSchema = new mongoose.Schema({
username: { type: String },
password: { type: String },
age: { type: Number}
})
puis je définit le model qui va me permettre de faire des requete à la base de donnée
et un point très très important c'est que le nom du model tu dois les mettres en anglais
lorsque tu as par exemple comme `persone` nom dans le model dans la base de donne ça sera stocker comme `people`, `stydy` => `stydies`
`user` => `users` ainsi de suite
var UserModel = mongoose.model("User", UserSchema)
var device = require("express-device")
var app = express()
app.set("port", process.env.PORT || 3000)
app.set("views", path.join(__dirname, "views"))
app.set("view engine", "ejs")
les valeur disponible sont
combined || common || dev || short || tiny
essay chacune de ces valeur tu va voir la sortie dans la console
app.use(logger("dev"))
app.use(device.capture())
app.use(bodyParser.urlencoded({ extended : true }))
app.use(express.static(path.join(__dirname, 'public')))
app.get("/", function(request, response) {
var users = [] // Un tableau qui va contenir les utilisateur à passer à la vue
UserModel.find({}, function(err, users) {
if(err) throw err
else {
users.push(users) // j'étant le tableau que j'ai declarer précédemment avec les résultats obtenu de la base de donnée
}
})
je passe comme deuxième paramètre un object de valeur qui seront utiliser dans la vue index comme `users`
response.render("index", {users: users})
console.log("Un visiteur demande la page index");
})
app.use(function(request, response, next) {
response.setHeader('Content-Type', 'text/plain')
response.status(404).send('Page introuvable')
console.log("Un utilisateur demande une page introuvable")
})
var server = http.createServer(app)
var io = require("socket.io").listen(server)
io.sockets.on('connection', function (socket) {
socket.emit('message', 'Vous êtes bien connecté !');
});
server.listen(app.get("port"), function() {
console.log("The server is running on http://localhost:%s", app.get("port"))
})
Edit: here is something (commented in French -- it comes from the french FAQ of fr.comp.lang.c++ --, I have no time for translation and think it is better to leave them than to remove them) which wraps FILE* call into a streambuf. This also is a show case of a use of private inheritance: ensuring that what could be a member is initialized before a base class. In the case of IOStream, the base class could as well receive a NULL pointer and then the member init() used to set the streambuf.
#include <stdio.h>
#include <assert.h>
#include <iostream>
#include <streambuf>
// streambuf minimal encapsulant un FILE*
// - utilise les tampons de FILE donc n'a pas de tampon interne en
// sortie et a un tampon interne de taille 1 en entree car l'interface
// de streambuf ne permet pas de faire moins;
// - ne permet pas la mise en place d'un tampon
// - une version plus complete devrait permettre d'acceder aux
// informations d'erreur plus precises de FILE* et interfacer aussi
// les autres possibilites de FILE* (entre autres synchroniser les
// sungetc/sputbackc avec la possibilite correspondante de FILE*)
class FILEbuf: public std::streambuf
{
public:
explicit FILEbuf(FILE* cstream);
// cstream doit etre non NULL.
protected:
std::streambuf* setbuf(char_type* s, std::streamsize n);
int_type overflow(int_type c);
int sync();
int_type underflow();
private:
FILE* cstream_;
char inputBuffer_[1];
};
FILEbuf::FILEbuf(FILE* cstream)
: cstream_(cstream)
{
// le constructeur de streambuf equivaut a
// setp(NULL, NULL);
// setg(NULL, NULL, NULL);
assert(cstream != NULL);
}
std::streambuf* FILEbuf::setbuf(char_type* s, std::streamsize n)
{
// ne fait rien, ce qui est autorise. Une version plus complete
// devrait vraissemblablement utiliser setvbuf
return NULL;
}
FILEbuf::int_type FILEbuf::overflow(int_type c)
{
if (traits_type::eq_int_type(c, traits_type::eof())) {
// la norme ne le demande pas exactement, mais si on nous passe eof
// la coutume est de faire la meme chose que sync()
return (sync() == 0
? traits_type::not_eof(c)
: traits_type::eof());
} else {
return ((fputc(c, cstream_) != EOF)
? traits_type::not_eof(c)
: traits_type::eof());
}
}
int FILEbuf::sync()
{
return (fflush(cstream_) == 0
? 0
: -1);
}
FILEbuf::int_type FILEbuf::underflow()
{
// Assurance contre des implementations pas strictement conformes a la
// norme qui guaranti que le test est vrai. Cette guarantie n'existait
// pas dans les IOStream classiques.
if (gptr() == NULL || gptr() >= egptr()) {
int gotted = fgetc(cstream_);
if (gotted == EOF) {
return traits_type::eof();
} else {
*inputBuffer_ = gotted;
setg(inputBuffer_, inputBuffer_, inputBuffer_+1);
return traits_type::to_int_type(*inputBuffer_);
}
} else {
return traits_type::to_int_type(*inputBuffer_);
}
}
// ostream minimal facilitant l'utilisation d'un FILEbuf
// herite de maniere privee de FILEbuf, ce qui permet de s'assurer
// qu'il est bien initialise avant std::ostream
class oFILEstream: private FILEbuf, public std::ostream
{
public:
explicit oFILEstream(FILE* cstream);
};
oFILEstream::oFILEstream(FILE* cstream)
: FILEbuf(cstream), std::ostream(this)
{
}
// istream minimal facilitant l'utilisation d'un FILEbuf
// herite de maniere privee de FILEbuf, ce qui permet de s'assurer
// qu'il est bien initialise avant std::istream
class iFILEstream: private FILEbuf, public std::istream
{
public:
explicit iFILEstream(FILE* cstream);
};
iFILEstream::iFILEstream(FILE* cstream)
: FILEbuf(cstream), std::istream(this)
{
}
// petit programme de test
#include <assert.h>
int main(int argc, char* argv[])
{
FILE* ocstream = fopen("result", "w");
assert (ocstream != NULL);
oFILEstream ocppstream(ocstream);
ocppstream << "Du texte";
fprintf(ocstream, " melange");
fclose(ocstream);
FILE* icstream = fopen("result", "r");
assert (icstream != NULL);
iFILEstream icppstream(icstream);
std::string word1;
std::string word2;
icppstream >> word1;
icppstream >> word2;
char buf[1024];
fgets(buf, 1024, icstream);
std::cout << "Got :" << word1 << ':' << word2 << ':' << buf << '\n';
}
Recommend
Multiple PIDs being stored in PID file
Deleting Cell value the cell in the next column is the same
Printing Values from a list without spaces in python 2.7
use jose.4.j to output JWK set endpoint?
search tuple with three elements inside list
IV Estimation with Cluster Robust Standard Errors using the plm package in R
File.renameTo turns everything into mess
Split image src attribute with plain vanilla JavaScript and no Regex
Counting words in a string in JAVA
REALLY remove a too large file from git push that was already deleted?
WPF Binding to UserControl´s DependencyProperty not working as expected
Matlab output matrix to file with a reasonable format
String replace with recursive dictionary values
Proper usage of Singleton getInstance method
Function taking iterator pair not working when run in parallel
Generate two words sentence from full sentence (combinations)
Custom Excel Function Data Type Issue
Can different parts of dplyr::summarize() be computed conditionally?
Get reference to currently active HTMLElement
Lua - get original table address from nested metatable __index method
Trouble implementing repeating elements in docopt
Using ASP.Net MVC Ajax and drop-down list on change
Check if one element equal the previous element R
detect a timestamp string in a list
Access control for images in web frontend
ASP.NET CustomValidator not firing the event
Why can list comprehension select columns of a matrix?
Convert complex config file to id,parent,key,value format
Javascript Exif information only showing after the first click of image in html page
get values separated by random spaces in lines from text file in shell
Load debug version of pre-built module via npm/webpack
Get image preview to another div on click
create a text file to a folder location as a operating system file?
Import spring boot app into another project
BSON ObjectID (Morphia) representation in Typescript/Angular2 Project
Perform segue after UIAlertController is dismissed
get rid of the row wrapper object in pyspark dataframes without using RDD api?
Group by Weeks for successive years
HTML img tag auto refresh browser causes image tearing
Python->Data Frame->Expanding the Data Frame
Perl: specify minimum version in env var?
Custom URL from a checkbox form
Pandas: reading data from PyODBC and parsing datetime from different columns
React router server side unexpected behaviour
laravel collective checkbox form
Catcomplete widget stopped working when updating jQuery UI from 1.8 to 1.12
Mustache js causing failed to load resource error
Automatically removing Private IP's in Route53 private hosted Zone
Intersection of two lists of ranges in Python
Is there a dynamic way to build my array so that I don't have to specify each key/element in it?
I can't properly return from a recursive function
PHP Array - accessing specific elements
SQL is run once for every row when .list() is called, despite having no associations
Early exit for Rx.Observable.retryWhen/timer
Google Bar Chart data preparation -- Group by Column
Syntax error using the WITH clause
parse prefix function such as Pow() with multiple parameters using FParsec
On selecting a textfield, adjust view height for keyboard
Performance of Primitive Data types VS their Wrapper class
Screen capture fails to capture whole screen using C++ and GDI
the fastest way to prepare data for RNN with numpy?
Assigning return to variable dosent work
In Visual Studio Code, launch a Console application in an external window
I find and jump to word in :tselect results?
vim: substitute specific character, but only after nth occurance
Get data from soap envelope zeep
Eclipse IDE processing emojis using surrogate pairs
Using multiple security providers for each URI in Symfony2
Camel Conditional Polling Consumer
gulp-typescript is compiling all .ts files not just those from specific location
Add href to description in _config.yml
wait for page reload with selenium?
Strange border glitch of an ImageView
calculate the difference between the two fields in Elasticsearch?
Annotation.toString() omits double quotes from String attributes
ambiguous associated type error when pattern matching over a HashMap::Entry (Error code E0223)
create index for select query with multiple OR conditions and AND conditions
Visual Basic Divide Double Randomly based on Divisor
Remove Blank Entries Imported By ArrayFormula
Python doesn't go automatically to next line when writing to CSV file
Toggle Visibility of my Divs in JavaScript
Starting a JQuery Div Drag by clicking on an image
quantify over all subsets in MiniZinc
spring data rest: How to publish a user management api
wrap a do-while style loop in a macro, maintaining 'continue' flow control?
delete GitHub repository connection from Brackets?
Rails - Store html templates in filesystem or database