事件循環:
非阻塞 I/O:NodeJS 非同步處理 I/O 操作,這表示它不會等待操作完成就繼續下一個任務。
範例:
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");
輸出:
Start End (contents of example.txt)
說明:
// 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;
範例:
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.'); }); }); }); }); });
輸出:
File written successfully. File contents: Hello, NodeJS! File appended successfully. File renamed successfully. File deleted successfully.
範例:
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/'); });
輸出:
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:
以上是Node.js 入門的詳細內容。更多資訊請關注PHP中文網其他相關文章!