Node Flashcards
http.createServer - what to require
var http = require(‘http’);
http.createServer - hello world
http.createServer(function(req,res){
res.writeHead(200,{‘Content-Type’: ‘text/html’});
res.end(‘Hello World’);
}).listen(8080);
use the “exports” keyword to make properties and methods available outside the module
exports.myDateTime = function() { return Date(); }
include a module
var dt = require(‘./myfirstmodule’);
what does the built-in Node module ‘http’ do
allows to transfer data over the HTTP protocol
If the response from the HTTP server is supposed to be displayed as HTML…
include HTTP header with the correct content type
res.writeHead(200, {‘Content-Type’: ‘text/html’})
the function passed into http.createServer has req argument - it represents…
the request from the client, as an object (http.IncomingMessage)
the built-in URL module can easily _ query string
split into readable parts
URL can have a query in it, using URL module, like this
var q = url.parse(req.url, true).query //will pick apart the url query var txt = q.year + " " + q.month //will render in text
in the URL, put /?year=2017&month=July and it will use these values in txt
file system (‘fs’) allows to work with the file system. use for …
reading, creating, updating, renaming and deleting files
read files with
fs.readFile()
how to read in an HTML file
inside http.createServer you place another function with fs.readFile('index.html',function(err,data){ //res.writeHead... //res.write... }
FS module has these methods for creating files
fs. appendFile()
fs. open()
fs. writeFile()
fs.appendFile() does…
appends specified content to a file
if the file doesn’t exist, it creates it
fs.open() takes a flag as second argument
if the flag is ‘w’ for writing, the specified file is open for writing
if the file doesn’t exist, an empty one is created