以下是Node.js的入门教程,适合零基础学习者快速上手:
node -v
npm -v
创建hello.js:
console.log("Hello Node.js!");
运行:
node hello.js
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// app.js
const math = require('./math');
console.log(math.add(2, 3)); // 5
// 文件操作示例
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// 创建HTTP服务器
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Node.js Server!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
npm init -y
npm install express # 本地安装
npm install -g nodemon # 全局安装
{
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
}
}
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) return console.error(err);
console.log(data);
});
const fs = require('fs').promises;
fs.readFile('file.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));
async function readFile() {
try {
const data = await fs.readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer(async (req, res) => {
const filePath = path.join(__dirname, 'public', req.url);
try {
const data = await fs.promises.readFile(filePath);
res.writeHead(200);
res.end(data);
} catch (err) {
res.writeHead(404);
res.end('File not found');
}
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
node --inspect app.js
建议从构建简单的API服务开始实践,逐步扩展到完整应用开发。注意异步编程和错误处理的正确使用,这是Node.js开发的关键点
下一篇:HTML iframe 使用指南