nodejs 学习
fs
读写文件删除文件
// 读取文件
// 创建文件
// 删除文件
fs.unlink('writeFile.txt', () => {
console.log('hello')
});
创建目录删除目录
// 新建目录(同步)
fs.mkdirSync('testDelete');
// 删除目录(同步)
fs.rmdirSync('testDelete');
// 新建目录并且将某个文件内容读取新建写入到新建目录中
fs.mkdir('testMove', function () {
fs.readFile('readme.txt', (err,data) => {
if(err) {
console.log(err);
return
}
fs.writeFile('./testMove/writeFile.txt',data,(err) => {
if(err) {
console.log(err)
}
})
})
});
fs.ReadStream文档
// 创建文件读取流
var readStreams = fs.createReadStream(__dirname + '/readme.txt');
var writeStreams = fs.createWriteStream(__dirname + '/write.txt');
readStreams.pipe(writeStreams);
http
// 创建服务器和返回html文件
const http = require('http');
const fs = require('fs');
const server = http.createServer((request, response) =>{
response.writeHead(200, {
"Content-Type": "text/html"
});
let myHtml = fs.createReadStream(__dirname + '/index.html', 'utf-8');
// 输出到响应中
myHtml.pipe(response);
});
server.listen(3001, '127.0.0.1');
request和response
request
req.method
req.headers
req.url
const http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
console.log(req.url)
res.writeHead(400, {
'content-type': 'text/html;charset=utf8'
})
if(req.url === '/index' || req.url === '/') {
res.end('首页!
')
}else if(req.url === 'list') {
res.end('list!')
}else {
res.end('404Pages')
}
if(req.method === 'POST') {
res.end('post')
}else if(req.method === 'GET') {
res.end('get')
}
})
server.listen(3000)
respone
- 响应状态码
- http状态码
- 200 请求成功
- 404 请求资源不存在
- 500 服务器错误
- 400 请求出现语法错位
- 304 请求的内容没有发成改变
- ...
const body = 'hello world';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain'
})
.end(body);
- 响应类型
- text/html
- text/css
- applicatiion/javascript
- image/jpeg
- application/json
路由
一些需要用到的工具
ts-node-dev