fs
const data = fs.readFileSync('./file.txt', 'utf-8')
console.log(data, '同步')
fs.readFile('./file.txt', 'utf-8', (err, data) => {
if (err) throw err
console.log(data, '异步')
})
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
readFile('./file.txt', 'utf-8').then(function (data) {
console.log(data, 'Promise');
}).catch(function (err) {
console.error('读取文件失败');
});
const fsp = fs.promises;
fsp.readFile('./file.txt', 'utf-8').then(data => {
console.log(data, 'fs.promises异步')
});
buffer
const buf1 = Buffer.alloc(10)
console.log(buf1)
const buf2 = Buffer.from('a')
console.log(buf2)
const buf3 = Buffer.from('中文')
console.log(buf3)
const buf4 = Buffer.concat([buf2, buf3])
console.log(buf4)
http
const http = require('http')
const fs = require('fs')
const server = http.createServer((request, response) => {
const { url, method, headers } = request
if (url === '/' && method === 'GET') {
fs.readFile('index.html', (err, data) => {
if (err) {
response.writeHead(500)
response.end('500 Page err')
return
}
response.statusCode = 200
response.setHeader('Content-Type', 'text/html')
response.end(data)
})
} else if (url === '/users' && method === 'GET') {
response.writeHead(200, {
'Content-Type': 'application/json'
})
response.end(JSON.stringify({
name: 'laowang'
}))
} else if (method === 'GET' && headers.accept.indexOf('image/*') !== -1) {
fs.createReadStream('./' + url).pipe(response)
} else {
response.writeHead(404)
response.end('404 Page Not Found')
}
})
server.listen(3000)
stream
const fs = require('fs')
const rs = fs.createReadStream('./img.png')
const ws = fs.createWriteStream('./img2.png')
rs.pipe(ws)