イベントループ:
ノンブロッキング 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 中国語 Web サイトの他の関連記事を参照してください。