Node.js 入门
模块导出
javascript
// math.js
const add = (a, b) => a + b
const subtract = (a, b) => a - b
module.exports = { add, subtract }
// 或使用 ES6
export { add, subtract }文件操作
javascript
const fs = require('fs').promises
// 读取文件
const content = await fs.readFile('file.txt', 'utf-8')
// 写入文件
await fs.writeFile('output.txt', 'Hello', 'utf-8')HTTP 服务器
javascript
const http = require('http')
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Hello World!')
})
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000')
})Express 框架
javascript
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('首页')
})
app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: '张三' },
{ id: 2, name: '李四' }
])
})
app.listen(3000)