Learn Node.js for Beginners with Teacher Liao Xuefeng

node.js simple touch
'use strict';
var test_1 = require('./test-1');
test_1('xiangzhipeng');
// read the file synchronously and asynchronously
try{
    var fs = require('fs');
    // fs.readFile('test-img.png','UTF-8',function(err,data){
    //     if(err){
    //         console.info(err);
    //     }else{
    //         console.info(typeof data);
    //     }
    // });

    //console.info(fs.readFileSync('test-img.png','UTF-8'));
}catch(err){
    console.info(err);
};
console.info('------------','Read files synchronously and asynchronously');

//write file
var data1 = 'I wrote the text asynchronously using Node.js';
var data2 = 'I wrote the text synchronously using Node.js';
// fs.writeFile('./write-test.txt',data1,function(err){
//     if(err){
//         console.info(err);
//     }else{
// console.info ('ok');
//     }
// });

//fs.writeFileSync('write-test.txt',data2);
console.info('------------','write file');

//stat file details
fs.stat('./write-test.txt',function(err,data){
    if(err){
        console.info(err)
    }else{
        //console.info(data);
        console.info(data.birthtime)
    }
});
console.info(fs.statSync('./write-test.txt').birthtime);//Get stat object synchronously

//input and output stream
var rs = fs.createReadStream('./write-test.txt','UTF-8');
rs.on('data',function(chunk){
    console.info('readStream:',chunk);
});
rs.on('end',function(){
    console.info('Reading finished');
});

var ws = fs.createWriteStream('./write-test.txt','UTF-8');
ws.write('I wrote the text using writeStream');
ws.write('finished');

//pipe file copying with input and output...
rs = fs.createReadStream('./write-test.txt','UTF-8');
ws = fs.createWriteStream('./copy.txt','UTF-8');
rs.pipe(ws);

//http module
var http = require('http');
var server = http.createServer(function(req,resp){
    console.info('Get the method and url of the HTTP request', req.method+" "+req.url);// Get the method and url of the HTTP request:
    resp.writeHead(200,{'Content-type' : 'text/html'});// Write HTTP response 200 to response, and set Content-Type: text/html:
    resp.end('<h1>Hello World</h1>');//Write the content of the response to the response
});
server.listen(8080);// Let the server listen on port 8080:
console.info('Server is running at http://127.0.0.1:8080');

//url module
var url = require('url');
//console.info(url.parse('http://user:[email protected]:8080/path/to/file?query=string#hash'));

//path module handles local file directories
var path = require('path');
var workDir = path.resolve('.');//Get the workspace directory
console.info(path.join(workDir,'pub','index.html'));


nodeJS implements server-side html return, file server
'use strict'
var fs = require('fs'),
    http = require('http'),
    url = require('url'),
    path = require('path');
//1. Establish a service port, provide access, parse the url to get the file directory and name in the url
//2. Get the project root directory and find the files needed by the client
//3. Read the file using the file input stream
//4. Use pipe to merge the input stream into the response and return

//Get the path of the project in the current server
var rootDir = path.resolve(process.argv[2] || '.');

//create service
var server = http.createServer(function(request,response){
    // get the file directory
    var pathname = url.parse(request.url).pathname;
    //Generate server-side file path
    var filePath = path.join(rootDir,pathname);

    fs.stat(filePath,function(err,stats){
        if(!err && stats.isFile()){ //If it is read and it is a file, pass in the file input stream
            response.writeHead(200);//response to send 200 status code
            console.info(filePath);
            fs.createReadStream(filePath,'UTF-8').pipe(response);
        }else if(!err && stats.isDirectory()){
            if(fs.existsSync('index.html')){
                fs.createReadStream(filePath+'index.html').pipe(response);
            }else if(fs.existsSync('default.html')){
                fs.createReadStream(filePath+'default.html').pipe(response);
            }
        }else{//Otherwise the error file does not exist
            response.writeHead(404);//The file does not exist, 404 response
            response.end('404 not Found');
        }
    });
});
//Listen on port 8080
server.listen(8080);
console.info('Server is running');

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326501736&siteId=291194637