Documents
Documents
js
1. Introduction to Node.js
What is Node.js?
- Node.js is an open-source, cross-platform JavaScript runtime environment that
executes JavaScript code outside of a web browser.
- It's built on Chrome's V8 JavaScript engine, allowing JavaScript to be used for
server-side scripting.
- Key Features of Node.js:
- Asynchronous and Event-Driven: Non-blocking I/O operations, which makes it
efficient and scalable.
- Fast Execution: The V8 engine compiles JavaScript into native machine code,
which boosts performance.
- Single Programming Language: Developers can use JavaScript for both
frontend and backend, streamlining development.
---
2. Environment Setup
Verify Installation
- Open the terminal (Command Prompt for Windows) and run the following
commands:
- `node -v` - Displays the Node.js version installed.
- `npm -v` - Displays the npm version installed.
- If both commands return version numbers, the installation was successful.
---
What is npm?
- npm (Node Package Manager) is the default package manager for Node.js. It
allows developers to install, update, and manage third-party packages (modules).
- Role of npm:
- Manage project dependencies.
- Distribute and share reusable code.
- Streamline project setup and configuration.
- Installing Packages:
- `npm install <package-name>`: Installs a package locally in the project
directory.
- `npm install -g <package-name>`: Installs a package globally, making it
available across projects.
- Managing Packages:
- `npm uninstall <package-name>`: Uninstalls a package from your project.
- `npm update <package-name>`: Updates a package to its latest version.
Installing Dependencies
- Example: Installing Express.js, a popular web framework:
- Run `npm install express`.
- This command installs Express and adds it to the `dependencies` section in
`package.json`.
- node_modules Folder: All installed packages are stored here.
- Reinstalling Dependencies:
- If you clone a project or share it, run `npm install` to install all listed
dependencies from `package.json`.
---
mkdir my-first-node-app
cd my-first-node-app
npm init -y
node app.js
module.exports = { add };
// app.js
const math = require('./math');
console.log(math.add(2, 3)); // Output: 5
Introduction to `console.log` for Output
- `console.log`: A simple way to output messages to the console.
- Encourage students to experiment with logging different data types: strings,
numbers, arrays, objects, etc.
- Example:
javascript
console.log("Hello, World!");
console.log(42);
console.log([1, 2, 3]);
console.log({ name: "Alice", age: 25 });
---