Node.js Basics
Updated: 03 September 2023
Basic Modules
Installing Prerequisites
Installing NodeJs
Install the necessary version of Node Node v8+ and NPM v5+
Confirm that node is installed
Also installing a node server globally
Installing MongoDb
Install Mongo from the Download page
Confirm that MongoDb is installed
How start a Node REPL environment
Can run standard javascript with
Alternatively, we can use eval with
To run a node script we use
This can be an absolute or releative path to the file
NodeJs Globals
We are providded with some additional objects and keywords on top of javascript
global
process
module.exports
orexports
Global
Any first level global
property is available without the keywords Some poperties of the global object are as follows:
process
require
module
console
__dirname
__filename
Processes
Every Node.js script is a process
We can interact with the process by:
env
Enviromnent variablesargv
Command-line argumentsexit()
Terminate the current process
Process exit codes can be specified
Import and Export Modules
module.exports
Global property to allow a script to export something for other modules to use
require
require() is a path to a file, or a name. This will import the necessary files that we need to read. JSON files can be imported directly as an object.
require can be used to import many types of modules as such:
Core Modules
Node has a lot of preinstalled modules, the main ones are as follows:
- fs: module to work with the file system, files and folders
- path: module to parse file system paths across platforms
- querystring: module to parse query string data
- net: module to work with networking for various protocols
- stream: module to work with data streams
- events: module to implement event emitters (Node observer pattern)
- child_process: module to spawn external processes
- os: module to access OS-level information including platform, number of CPUs, memory, uptime, etc.
- url: module to parse URLs
- http: module to make requests (client) and accept requests (server)
- https: module to do the same as http only for HTTPS
- util: various utilities including promosify which turns any standard Node core method into a promise-base API
- assert: module to perform assertion based testing
- crypto: module to encrypt and hash information
fs
Handles file system operations
- fs.readFile() reads files asynchronously
- fs.readFileSync() reads files synchronously
- fs.writeFile() writes files asynchronously
- fs.writeFileSync() writes files synchronously
Reading a File
Writing to a file
path
Can join a path relativley as:
Or absoltely as:
Event emitters
We can create an EventEmitter with events
and using this we can create, listen and trigger events
Single trigger
Output Job was pronounced done at ____________
Mutiple triggers
Output
Single Execution of Handler
Output Who's there?
Modular events
We can use the observer pattern to modularize code. This allows us to customize modular behaviour without modifying the module.
jobs.js
main.js
HTTP Client
Get
Request and Response
Making an HTTP Request using http from NodeJs Core. Will receive data in chunks as follows http-get-no-buff
Alternatively, the data can be aded to a buffer until the response is complete as below http-get.js
Processing JSON
In order to get JSON the full response is needed, after which we parse the json to a response object
http-json-get.js
Post
To do a post we require a little but more information to be configured as such:
http-post.js
HTTP Server
We can use node http-server.js
to run the server, we can also use node-dev
to run the server and refresh on filechange.
http-server.js
http.createServer
creates a server with a callback function which contains a response handler code
res.writeHead(200, {'Content-Type': 'text/plain'})
sets the right status code and headers
res.end()
event handler for when response is complete
listen()
specifies the port on which the server is listening
Processing a request
We can process an incoming request by reading the request properties with the following:
httP-server-request-processing.js