Node.js syntax #
Node.js as a server-side JavaScript runtime, shares a significant portion of its syntax with browser-side JavaScript.
However, it introduces some unique elements tailored for server-side operations.
Below is an overview of the basic common syntax in Node.js:
Variables and Data Types: #
In Node.js, declaring variables is similar to JavaScript. Use var, let, or const to declare variables, with let and const being preferred due to block-scoping.
let message = "Hello, Node.js!";
const PI = 3.14;
Node.js supports common data types like strings, numbers, booleans, arrays, and objects.
Functions: #
Defining functions in Node.js is akin to JavaScript. Use the function keyword or utilize arrow functions for concise syntax.
function greet(name) {
return `Hello, ${name}!`;
}
// Arrow function
const add = (a, b) => a + b;
Asynchronous Programming: #
Node.js excels in asynchronous operations. Employ callbacks, promises, or async/await syntax for managing asynchronous tasks.
// Callback
readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
// Promises
readFile('file.txt')
.then(data => console.log(data))
.catch(err => console.error(err));
// Async/Await
async function readAndLog() {
try {
const data = await readFile('file.txt');
console.log(data);
} catch (err) {
console.error(err);
}
}
Modules: #
Node.js relies on a module system to organize code. Use require to import modules, and module.exports or exports to expose functionality.
// Exporting
const sum = (a, b) => a + b;
module.exports = sum;
// Importing
const sum = require('./sum');
File System Operations: #
Node.js provides modules for file system operations. fs is commonly used for reading, writing, and manipulating files.
const fs = require('fs');
// Reading a file
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Writing to a file
fs.writeFile('newFile.txt', 'Content to write', err => {
if (err) throw err;
console.log('File written successfully.');
});
HTTP Module: #
Node.js includes an HTTP module for creating web servers. Below is a basic example:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Event Emitters: #
Node.js utilizes an event-driven architecture. Core modules, as well as user-defined objects, can emit events. Use the events module for handling events.
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('Event emitted!');
});
myEmitter.emit('event');
Understanding the basic syntax in Node.js is fundamental for server-side development. While sharing similarities with client-side JavaScript, Node.js introduces modules and features tailored for server environments, emphasizing asynchronous operations, file system manipulations, and event-driven programming. With this foundation, developers can explore and leverage the extensive Node.js ecosystem for building scalable and performant applications.