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
fs.writeFile()
replaces the specified file and content if it exists
if the file doesn’t exist, a new file with the new specified content will be created
to delete a file with FS…
use the fs.unlink() method
rename files with
fs.rename(old name, new name)
url.parse() does…
parses an address, returns a URL object with each part of the address as properties
url.parse(address, true)
The NPM program is installed on your computer
when you install Node.js
A package in Node.js contains
all the files you need for a module.
Modules are JavaScript
libraries you can include in your project.
NPM creates a folder named
“node_modules”, where the package will be placed. All packages you install in the future will be placed in this folder.
Include the newly installed package
the same way you include any other module: var uc = require('upper-case');