This work is produced by John Häggerud at Linnaeus University.
All content in this work excluding photographs, icons, picture of course literature and Linnaeus University logotype and symbol, is licensied under a
Creative Commons Attribution 4.0 International License.
If you change the content do not use the photographs, icons, picture of the course literature or Linnaeus University logotype and symbol in your new work!
At all times you must give credit to: ”Linnaeus university” with the link https://webbprogrammerare.se and to the Creative Common-license above.
const http = require('http') // core module
const thirdPartyModule = require('someThirdPartyModule') // installed module
const myLocalModule = require('./lib/myLocalModule') // own local module
ECMAScript modules? https://nodejs.org/api/esm.html
Blocking
<?php
$homepage = file_get_contents("http://www.example.com");
echo $homepage;
// Must wait to do stuff here...
?>
Non-blocking - asynchronous - Callback pattern
let request = require("request")
request('http://www.example.com', (error, response, body) => {
if (!error && response.statusCode === 200) {
console.log(body) // Show the HTML for the homepage.
}
...
})
// ... don't have to wait to do stuff here
let requestHandler = (req, res) => {
let body = req.body // Contains the POST body the client sends
try {
let json = JSON.parse(body)
res.end(json.user.username)
}
catch(e) {
res.end("FAIL")
}
}
A package manager for Node.js (https://www.npmjs.com/)
# installs all dependencies in package.json
npm install
# installs the package lodash
npm install lodash
Use npm to install others modules into your project!
# Add to package.json under dependencies
npm install mocha
# Add to package.json under devDependencies
npm install mocha --save-dev
# Install globally on computer - does not add to package.json
npm install mocha -g
Should node_modules be in your .gitignore?
https://www.gitignore.io/
Use npx to execute a module (and install it temporarily)
# Execute eslint
npx eslint .
Bundled with npm version 5.2+
"dependencies": {
"lodash": "^3.7.2"
}
npm install
could install 3.9.9npm install
could install 3.7.9npm install
will install latest versionnpm update
- check for newer versions, bug fixes...Watch demo provided as a resource