Node.js is a JavaScript runtime
It may be used to:
npm = Node package manager
is included in the node.js installation
Download from https://nodejs.org
Major releases every 6 months; long-term-support releases every 12 months
The npm registry is an online registry consisting primarily of open source JavaScript packages
examples: most depended upon packages
major package managers for the npm registry:
Both public packages and private projects are managed via a configuration file named package.json
In order to add dependencies - start out with an empty package.json configuration:
{}
Alternative: create a package.json with some content via via npm init
(or npm init -y
for default options)
Add dependencies via e.g.:
npm install lodash bootstrap
When developing a reusable library to be published on the npm package registry:
Install dependencies that are only needed for development as dev-dependencies:
npm install eslint --save-dev
Effects of the previous npm install
commands:
package.json
- lists minimum versions of the packages we just installednode_modules
- folder that contains all installed packagespackage-lock.json
- lists exact versions of all packages in node_modules
The file package.json
now lists dependencies together with a version specifier
The version specifier typically uses semantic versioning: major.minor.patch
possible configurations:
"bootstrap": "4.3.1"
- exactly this version"bootstrap": "~4.3.1"
- patch version updates allowed - for example to 4.3.2
"bootstrap": "^4.3.1"
- minor version updates allowed - for example to 4.4.0
package-lock.json
lists exact versions for all dependencies and their recursive dependencies
contains the actual packages
this should not be put under version control - can be recreated from package.json
by running npm install
(without any arguments)
Npm can be used to execute scripts / commands that are needed for development, for example:
npm run test
- would run unit testsnpm run build
- would create a buildnpm run start
npm run deploy
Some npm scripts have shorthands, notably npm test
and npm start
Npm scripts are configured in package.json
:
{
"scripts": { "start": "node run-server.js" }
}
Node packages may be installed globally on a computer or may be executed directly from the npm registry
direct execution (without installation):
npx cowsay hello
global installation of cowsay
:
npm install -g cowsay
cowsay hello
hello.js:
console.log('Hello world!');
running it:
node hello.js
with debugging: F5
without debugging: Ctrl + F5
to determine how a JavaScript file should be run:
with a JavaScript file open, open the "Run" sidebar
select create a launch.json file - Node.js to create a file under .vscode/launch.json
possible configuration entries (.vscode/launch.json):
{
"name": "Run current file",
"type": "node",
"request": "launch",
"program": "${file}",
"skipFiles": ["<node_internals>/**"]
}
{
"name": "Run index.js",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/index.js",
"skipFiles": ["<node_internals>/**"]
}
Node programs can import objects from so-called modules
3 categories:
standard JavaScript imports:
import { platform, release } from 'os';
older, node-specific variant:
const { platform, release } = require('os');
to use the import
syntax in a node project, declare it as a module in package.json
:
{
"type": "module"
}
A JavaScript file that exports objects is called a module
example of a module with modern syntax:
const message1 = 'hello!';
const message2 = 'have a nice day!';
export { message1, message2 };
there may be one default export
const mainMessage = 'xyz';
const message1 = 'hello!';
const message2 = 'have a nice day!';
export { message1, message2 };
export default mainMessage;
local modules are referenced via relative file paths:
import mainMessage, { message1 } from './messages.js';
in node, the filename extension is optional:
import mainMessage, { message1 } from './messages';
older, node-specific, export syntax:
const message1 = 'hello!';
const message2 = 'have a nice day!';
module.exports.message1 = message1;
module.exports.message2 = message2;
// shorthand
exports.message3 = 'Bye';
default export:
const mainMessage = 'xyz';
module.exports = mainMessage;
node has different global objects than in the browser
browser-only globals:
document
localStorage
, sessionStorage
window
(global namespace) - alternative name globalThis
node-only globals:
process
(e.g. process.argv
)__filename
and __dirname
global
(global namespace) - alternative name globalThis
process
is a global
process.argv
(command line arguments)process.cwd()
process.exit()
exercise: implement a program that can be run like this:
node sum.js 1 2 3
output:
the sum is 6
Examples:
asynchronous via promises (recommended):
import { readFile } from 'node:fs/promises';
asynchronous via callbacks:
import { readFile } from 'node:fs';
synchronous:
import { readFileSync } from 'node:fs';
import { writeFile } from 'node:fs/promises';
await writeFile('message.txt', 'hello world');
This will write to a text file in UTF-8 encoding.
const fileContent = await readFile('package.json', 'utf8');
When reading files as text, we must specify an encoding (in this case, UTF-8)
const folderContent = await readdir('.');
console.log(folderContent);
import http from 'http';
const requestHandler = (req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
};
const server = http.createServer(requestHandler);
server.listen({ port: 3000 });
(see https://nodejs.org/en/docs/guides/getting-started-guide/)