Home > Article > Web Front-end > Getting Started with Node JS
Event Loop:
Non-blocking I/O: NodeJS handles I/O operations asynchronously, meaning it doesn’t wait for operations to complete before moving on to the next task.
Example:
const fs = require('fs'); console.log("Start"); // Reading a file asynchronously fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); console.log("End");
Output:
Start End (contents of example.txt)
Explanation:
// Named export export const add = (a, b) => a + b; // Default export export default function subtract(a, b) { return a - b; }
// Named import import { add } from './math.js'; // Default import import subtract from './math.js';
// Using module.exports module.exports.add = (a, b) => a + b; // Using exports shorthand exports.subtract = (a, b) => a - b;
// Importing modules const math = require('./math.js'); const add = math.add; const subtract = math.subtract;
Example:
const fs = require('fs'); // Writing to a file fs.writeFile('example.txt', 'Hello, NodeJS!', (err) => { if (err) throw err; console.log('File written successfully.'); // Reading the file fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log('File contents:', data); // Appending to the file fs.appendFile('example.txt', ' This is an appended text.', (err) => { if (err) throw err; console.log('File appended successfully.'); // Renaming the file fs.rename('example.txt', 'newExample.txt', (err) => { if (err) throw err; console.log('File renamed successfully.'); // Deleting the file fs.unlink('newExample.txt', (err) => { if (err) throw err; console.log('File deleted successfully.'); }); }); }); }); });
Output:
File written successfully. File contents: Hello, NodeJS! File appended successfully. File renamed successfully. File deleted successfully.
Example:
const http = require('http'); // Creating a server const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n'); }); // Listening on port 3000 server.listen(3000, '127.0.0.1', () => { console.log('Server running at http://127.0.0.1:3000/'); });
Output:
Server running at http://127.0.0.1:3000/
Example:
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Welcome to the homepage!\n'); } else if (req.url === '/about') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Welcome to the about page!\n'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found\n'); } }); server.listen(3000, '127.0.0.1', () => { console.log('Server running at http://127.0.0.1:3000/'); });
Output:
The above is the detailed content of Getting Started with Node JS. For more information, please follow other related articles on the PHP Chinese website!