Node.js Get Started
Getting Started with Node.js
Node.js is a JavaScript runtime built on Chrome's V8 engine. It allows you to run JavaScript outside the browser, making it ideal for backend development, command-line tools, and API services.
1. Install Node.js
Download and install Node.js from the official website. It comes with npm (Node Package Manager) by default.
2. Check Installation
Verify that Node.js and npm are installed by running:
node -v npm -v
3. Run Your First Node.js Program
Create a file app.js and add the following code:
console.log("Hello, Node.js!");
Run it using:
node app.js
4. Using Built-in Modules
Node.js provides core modules like fs, http, and path.
Example:
const fs = require('fs'); fs.writeFileSync('test.txt', 'Hello from Node.js'); console.log('File created!');
5. Create a Simple HTTP Server
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, World!'); }); server.listen(3000, () => console.log('Server running on port 3000'));
Run the script and visit http://localhost:3000 in your browser.
6. Install Packages with npm
npm init -y npm install express
7. Create a Basic Express Server
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello, Express!'); }); app.listen(3000, () => console.log('Express server running on port 3000'));
8. Run Scripts with package.json
Modify package.json
to add a script:
"scripts": { "start": "node app.js" }
Run it using:
npm start
9. Use Nodemon for Auto-Reloading
Install and use Nodemon for development:
npm install -g nodemon nodemon app.js
10. Next Steps
- Explore asynchronous programming with callbacks, promises, and async/await.
- Work with databases like MongoDB, PostgreSQL, or MySQL.
- Build REST APIs with Express.js.
- Deploy your application using Docker, AWS, or Heroku.
Previous Next