Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Node.js学习 #3

Open
hujiejeff opened this issue Jun 29, 2020 · 2 comments
Open

Node.js学习 #3

hujiejeff opened this issue Jun 29, 2020 · 2 comments

Comments

@hujiejeff
Copy link
Owner

No description provided.

@hujiejeff
Copy link
Owner Author

文件读写

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
Copy link
Owner Author

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');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant