Node.js and Express Quick Reference and Tips
______________________________________________
Ubuntu Install:
$ sudo apt-get update
$ sudo apt-get install nodejs npm
Version:
$ nodejs --version
$ npm --version
The default package version will be older than using the current version. It's typical to choose the LTS version.
Use the default LTS tab on the Download page on nodejs.org for the current version, which should install node and npm, as well.
$ cd /usr/local/lib/
$ mkdir nodejs
$ cd nodejs
$ curl -sL https://nodejs.org/dist/v10.15.3/node-v10.15.3-linux-x64.tar.xz
$ sudo tar -xJvf node-v10.15.3-linux-x64.tar.xz -C /usr/local/lib/nodejs/
Update the user profile:
$ vi ~/.profile
# Nodejs
VERSION=v10.15.3
DISTRO=linux-x64
export PATH=/usr/local/lib/nodejs/node-$VERSION-$DISTRO/bin:$PATH
<esc>:wq
Test the install the same way as the apt-get installation.
Install other packages needed by NPM installer:
$ sudo apt-get install gcc g++ make
Set-up the firewall:
$ sudo ufw allow proto tcp to any port 80
$ sudo ufw allow proto tcp to any port 443
$ sudo ufw enable
______________________________________________
Upgrade existing version:
$ nvm install --lts
View all installed NVM instances:
$ nvm ls
Switch active version:
$ nvm use 10.15.3
Set version as default:
$ nvm alias default 10.5.3
______________________________________________
Create Hello World:
$ cd /home/myadmin/test/
$ vi helloworld.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(80);
<esc>:wq
$ node helloworld.js
Using a local web browser:
http://localhost/
______________________________________________
Init = New Project Wizard
$ cd /home/myadmin/
$ mkdir newapp
$ cd mkdir
$ npm init
- Asks for project name, initial version, description, entry poing (main file name), test command, git repository, keywords, license (defaults ISC)
Install using $npm install modnm.
- Use --save to save into app's dependencies list.
- Use -g to make a global install instead of just this app install.
______________________________________________
Modules are equivalent to a JS library to import, or a LotusScript/VBScript library to Use.
They are loaded for use via the require function being assigned to a variable.
var myHttp = require('http');
Modules load an object instance, such as HTTP. The myhttp object then has methods and properties or other "sub" objects that can be created.
myHttp.createServer();
Custom/local modules are installed typically by relative path:
var myCustomMod = require('../MWMods/mod2');
This references a custom module, one folder up, and back down into the MWMods folder to the mod2.js module.
Common Modules:
var url = require('url');
var uAddr = 'https://www.mindwatering.com/MWSupport.nsf';
var uParse = url.parse(uAddr, true);
console.log(uParse.host); // www.mindwatering.com
console.log(uParse.pathname); // MWSupport.nsf
var fileSystemFiles = require('fs');
fileSystemFiles.readFile();
fileSystemFiles.open();
fileSystemFiles.writeFile();
fileSystemFiles.appendFile();
fileSystemFiles.rename();
fileSystemFiles.unlink(); //delete file
const exp = require('express');
const app = exp();
const port = 80;
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.post('/', function (req, res) {
res.send('Hello World Post Response!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
______________________________________________
Module Install Locations:
Non global:
$ npm install modnm
Installs into current folder, into a folder (new if necessary), called node_modules.
e.g. /home/myadmin/hellowold/node_modules/
Global:
$ npm install -g modnm
$ npm root -g
Installs into global folder. In Ubuntu,
/usr/local/lib/node_modules/
Example folder structure for "mwapp" w/starting point "mwapp.js":
/home/mwadmin/mwapp/
- - - - - - - - - - - - - /node_modules/
- - - - - - - - - - - - - /mwapp.js
- - - - - - - - - - - - - /package.json
The package.json contains the dependancies. The mwapp.js is the application/web site. The node_modules are where the installed modules are located, unless global.
If you take on the npm init defaults, then the starting point/file name would be index.js, rather than mwapp.js as in this example.
______________________________________________
Creating a Private Module.
Create a JS file for your module and add to your main app directory.
e.g. reqLogger.js
module.exports = function(req, res, next) {
console.log(req.ip);
next(); // allows code to progress to next call, and if error to progress to error handler
}
In the main app JS, require your module and use it.
e.g. index.js
const exp = require('express');
const app = exp();
const port = 80;
const reqLogger = require("./reqLogger.js");
app.use(reqLogger()); // call the function
app.get('/', function (req, res) {
res.send('Hello World!');
});
______________________________________________
Express General Info:
Express Hello World example:
const exp = require('express');
const app = exp();
const port = 80;
app.get('/', function (req, res) {
res.send('Hello World!');
});
An application can be made up of more than Express instance. In this example, there is just one application instance named app.
The app.get is the HTTP METHOD in lowercase, for this example the method is the lowercase HTTP standard Get method. Methods include: get/put/update/delete/post).
The "/" is the HTTP endpoint PATH. In previous technologies it would be the location or virtual server, in Express, it is called the PATH.
The function(req, req) is the main function for the path '/' for the application app. The function has the REQUEST, req, and the RESPONSE, res.
The req object contains what the browser sent. The res object is what the app returns back to the client browser, via res.send().
To load static pages, image, and files, you might set-up the following:
/home/mwadmin/mwapp/
- - - - - - - - - - - - - /node_modules/
- - - - - - - - - - - - - /index.js
- - - - - - - - - - - - - /package.json
- - - - - - - - - - - - - /images/
- - - - - - - - - - - - - /files/
To return them w/ an Express-enabled app, you would add the following "middleware" static call. Typically, there would be options added for caching-control and to disable directory browsing. Most of us don't want our directories browsed.
So realistically, it might look like:
var fileOpts = {
dotfiles: 'ignore',
etag: false,
extensions: ['html', 'xml', 'docx', 'odt', 'ods', 'odf', 'odp', 'odb', 'doc', 'txt'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
}var imgOpts = {
dotfiles: 'ignore',
etag: false,
extensions: ['jpg', 'jpeg', 'png', 'gif'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
}
exp.static('files', fileOpts);
exp.static('images', imgOpts);
If the folder name, e.g. images, doesn't match the url path, e.g. pictures, then you have to do this:
app.use('/pictures', express.static('images'));
There is no passthru HTML like in Domino, or printing HTML via JS in Express. If you have HTML to return, structure your app to return it as a static file/asset, via exp.static(). If you want to return one file, you can also use res.sendFile().
Node.js and Express Error Handling:
For synchronous code, nothing specific has to be done. Error handling from asynchronous functions must be handled by the middleware (routes/connectors) we are using/writing and it must forward the error "up" via the next option. If/then example:
const exp = require('express');
const fs = require('fs');
const app = exp();
const port = 80;
app.get('/', function (req, res, next) {
fs.readFile('/report.txt', function (err, data) {
if (err) {
next(err) // forward error to Express if file isn't there or cannot be read.
} else {
res.send(data) // send the report contents back to user
}
})
})
Try/catch example with a time-out:
const exp = require('express');
const domDb = require('domino-db');
const app = exp();
const port = 80;
app.get('/', function (req, res, next) {
setTimeout(function () {
try {
// . . . code goes here . . .
} catch (err) {
next(err)
}
}, 100)
})
// handle for 404 status
app.use(function (req, res, next) {
res.status(404).send("Sorry can't find that!")
})
previous page
|