node.js learning notes arrangement

Keywords: Javascript encoding Web Development Web Server

(1) automatic construction of front-end projects

1. Create myProject project files and corresponding folders

var projectData ={
    'name':'myProject',
    'fileData':[
        {
            'name':'css',
            'type':'dir'
        },{
            'name':'js',
            'type':'dir'
        },{
            'name':'images',
            'type':'dir'
        },{
            'name':'index.html',
            'type':'file',
            'content' : '<html>\n\t<head>\n\t\t<title>title</title>\n\t</head>\n\t<body>\n\t\t<h1>Hello</h1>\n\t</body>\n</html>'
        }
    ]
};

var fs = require('fs');

if(projectData.name){
    // Create project folder
    fs.mkdirSync(projectData.name);
    var fileData = projectData.fileData;
    if(fileData && fileData.length){
        fileData.forEach(function(file){
             //File or folder path
             file.path = './'+projectData.name +'/'+ file.name;
             //Create files or folders based on type
             file.content = file.content || '';

             switch(file.type){
                 case 'dir':
                     fs.mkdirSync(file.path);
                     break;

                 case 'file':
                     fs.writeFileSync(file.path,file.content);
                     break;
                 default:
                     break;
             }

        });
    }

}

2. Package multiple files automatically

var fs = require('fs');
var filedir = './myProject/dist';

fs.exists(filedir,function(isExists){
    if(!isExists){
       fs.mkdirSync(filedir);
    }
    fs.watch(filedir,function(ev,file){
        //As long as one file changes, we need to read and merge all files under the folder
        fs.readdir(filedir,function(err,dataList){
            var arr = [];
            dataList.forEach(function(file){
                if(file){
                    //statSync view file properties
                    var info = fs.statSync(filedir + '/' +file);
                    //mode file permission
                    if(info.mode === 33206){
                        arr.push(filedir + '/' +file);
                    }
                }
            });
            //Read the contents of the file in the array
            var content = '';
            arr.forEach(function(file){
                var c = fs.readFileSync(file);
                content += c.toString()+'\n';
            });
           //Merge content in file
           fs.writeFileSync('./myProject/js/index.js',content);

        })

    });
});

(2) using node for web development

1. Build an http server to process http requests sent by users

//Load an http module
var http = require('http');
//Create and return a web server object through createServer under http module
var server = http.createServer();
//Open the HTTP server listening connection. The server will not work until the listen method is called
server.listen(8000,'localhost');
//Is the server listening for connections
server.on('listening',function(){
    console.log("listening..........");
});
//Triggered every time a request is received, there may be multiple requests per connection (in the case of an HTTP keep alive connection).
server.on('request',function(){
     res.write('<p>hello</p>');
     res.end();
});

2. The request method has two parameters: request and response

1) request: an instance of http.IncomingMessage to obtain some requested information, such as header information, data, etc
Httpmission: version of http protocol used
headers: data in the request header
url: requested address
Method: method of request

2) response: an instance of http.ServerResponse, which can output a response to the requested client
write (chunk,encoding): Send a data block to the corresponding body
end (chunk,encoding): when all text and header messages are sent, the method is called to tell that the server data has been sent to completion. This method must be called after the completion of the information transmission, and is the last call.
statusCode: this property is used to set the returned status code
setHeader (name,value): set the return header information
writeHead (statusCode,reasonPhrase,headers) can only be used once in the current request, and must be called before response.end ().

3. Use fs module to separate behavior

var http = require('http');
var url = require('url');
var fs = require('fs');

var server = http.createServer();
//Path to html file
var htmlDir = __dirname + '/html/';
server.on('request',function(request,response){
    var urlStr = url.parse(request.url);
    //Match the corresponding html file according to pathname
    switch(urlStr.pathname){
        case '/':
            sendData(htmlDir + 'index.html',request,response);
            break;
        case '/user':
            sendData(htmlDir + 'user.html',request,response);
            break;
        case '/login':
            sendData(htmlDir + 'login.html',request,response);
            break;
        default:
            //Deal with other situations
            sendData(htmlDir + 'err.html',request,response );
            break;
    }
});

function sendData(file,request,response){
    //Read the file. If it exists, the corresponding read content will be returned. If it does not exist, the error message will be returned
    fs.readFile(file,function(err,data){
        if(err){
            response.writeHead(404,{
                'content-type':'text/html;charset=utf-8'
            });
            response.end('<h1>Page does not exist</h1>')
        }else{
            response.writeHead(200,{
                'content-type':'text/html;charset=utf-8'
            });
            response.end(data);
        }
    })
}
server.listen(8000,'localhost');

Posted by Spitfire on Sun, 08 Dec 2019 22:35:07 -0800