hujiejeff / hujiejeff.github.io

https://hujiejeff.github.io
0 stars 0 forks source link

Node.js学习 #3

Open hujiejeff opened 4 years ago

hujiejeff commented 4 years ago

文件读写

let fs = require('fs');
//异步读写文件
fs.readFile('./nodejs/example.txt', 'utf-8', function(err, data) {
    if (err) {
        console.log(err);
    } else {
        console.log(data);
        fs.writeFile('./nodejs/after.txt', data, function(err) {
            if (err) {
            console.log('write error');
            }

        });
    }
});

//获取文件信息
fs.stat('./nodejs/example.txt', function(err, stat) {
    if (err) {
        console.log(err);
    } else {
        console.log(stat.isFile());
        console.log(stat.isDirectory());
        console.log(stat.birthtime.toLocaleDateString());
        console.log(stat.mtime.toLocaleDateString());
    }
});

//写流

let writeStream = fs.createWriteStream('./nodejs/stream.txt', 'utf-8');
writeStream.write('hello');
writeStream.write('from write stream');
writeStream.end();

//读流
let readStream = fs.createReadStream('./nodejs/stream.txt', 'utf-8');
readStream.on('data', function (chunk) {
    //数据可读,反复调用
    console.log('on:' + chunk);
});
readStream.on('end', function () {
    //读到末尾
    console.log('end');
});

readStream.on('error', function (err) {
    //读取出错
    console.log('ERROR:' + err);
});

//管道pipe,复制

let rs = fs.createReadStream('./nodejs/example.txt');
let ws = fs.createWriteStream('./nodejs/copied.txt');

rs.pipe(ws);
hujiejeff commented 4 years ago

http

let http = require('http');
let server = http.createServer(function(request, response) {
    console.log(request.headers)
    console.log(request.method + ":" + request.url);
    response.writeHead(200, {
        'Content-Type': 'text/html'
    });
    response.end('<h1>Hello World</h1>');
});
server.listen(3000);
console.log('server is running on 3000');