Quick introduction to NodeJS
This article introduces NodeJS, one of the most popular and powerful Javascript server frameworks. Hopefully after reading/following this, you will decide to explore further into its capabilities. Happy coding!
1. What is Node.js?
Node.js is a JavaScript runtime built on Chrome’s V8 engine that allows you to run JavaScript on the server side. It is great for building scalable, event-driven applications, such as web servers, APIs, and real-time applications.
2. Install Node.js
- Visit the Node.js website and download the LTS (Long Term Support) version.
- After installation, verify by running:
node -v
npm -v
npm
is Node’s package manager, which helps install libraries and dependencies.
3. Create a Simple Web Server
- Create a new folder for your project:
mkdir node-tutorial
cd node-tutorial
- Initialize a new Node.js project:
npm init -y
This will create a package.json
file that stores project settings and dependencies.
- Create a simple web server:
- Create a file called
server.js
:
// server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
- Run the server:
node server.js
Visit http://localhost:3000 in your browser to see the “Hello World” message.
4. Using NPM Packages
- Let’s use a package called
express
, a popular web framework for Node.js.
- Install express:
npm install express
- Update
server.js
:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
- Run the server again:
node server.js
You should now see “Hello from Express!” at http://localhost:3000.
5. File Structure Best Practices
Organise your project like this for larger applications:
node-tutorial/
│
├── package.json
├── server.js
└── routes/
└── index.js
└── controllers/
└── userController.js
6. Nodemon for Auto-Restarting
To automatically restart the server when you change files, use nodemon
:
- Install globally:
npm install -g nodemon
- Run the server with nodemon:
nodemon server.js
7. Conclusion
You’ve set up a simple Node.js project with a web server and Express. From here, you can explore more advanced features like working with databases (MongoDB, MySQL), middleware, and deploying applications.