NodeJS Series II: initial understanding of NodeJS built-in fs module

1. Introduction to FS module

fs is the file system, which is the file operation API provided by NodeJS. fs module is used to read and write system files and directories. It is a very important module. The operation of files is based on it. All the methods of this module are synchronous and asynchronous. Let's briefly introduce the common methods of fs module.

2. Use fs module for simple read and write operation

  1. Read file = > readfile and readfilesync
 fs.readFile(file_name[, options],function(err,data){
     //Asynchronous read with two required and one optional parameters
     //Required parameters: file file name, callback function. The first parameter of the callback function is to read error information, and the second is the data in the file
     //An optional parameter: options this parameter is an object containing {encoding, flag}. The default encoding is binary and the flag is' w '
 })
 fs.readFileSync(file_name[, options])//Synchronous read with a required parameter and an optional parameter, as above
The simple implementation is as follows:
var fs=require('fs');   //Introduce fs module
//Asynchronous read
fs.readFile('aaa.txt',function(err,data){
    if(err){
        console.log('Read error');
    }else{
        console.log('Asynchronous read:'+data.toString());//Because data returns binary data, you need to use toString() method conversion or optional parameters to fill in the text encoding utf-8
    }
});
fs.readFile('aaa.txt','utf-8',function(err,data){
    if(err){
        console.log('Read error');
    }else{
        console.log('Asynchronous read:'+data);
    }
});
//Synchronous read
var data=fs.readFileSync('aaa.txt');
console.log('Synchronous read:'+data.toString());
var data=fs.readFileSync('aaa.txt','utf-8');
console.log('Synchronous read:'+data);

The results are as follows:

2. Write file = > write file and write filesync
writeFile() directly opens the file in w mode by default, so if the file exists, the contents written by this method will overwrite the contents of the old file. If the file does not exist, a new file will be created

fs.writeFile(file_name,data[, options],function(err){
     //Asynchronous write with three required and one optional parameters
     //Three required parameters: file name, file information written by data, and function, a callback function. The parameters of the callback function are write error information
     //An options parameter: optionsThis parameter is an object that contains {encoding, mode, flag}. The default code is utf8, the mode is 0666, and the flag is' w '
 })
 fs.writeFile(file_name,data[, options])//Synchronous write has two required parameters and one optional parameter. The meaning of the parameter is one less callback function
var fs=require('fs');
//Asynchronous writing
fs.writeFile('aaa.txt','Write file information',function(err){
    console.log(err);
})
//Synchronous writing
fs.writeFileSync('aaa.txt','Write file information');

Results:

3. other

. . . . . .

4. Small practice of modules

Here, the fs module is combined with the http module contacted before to make a small integration, write a simple small demo from the server creation to the response foreground to find the file and do the corresponding return:

var http=require('http');
var fs=require('fs');
var querystring=require('querystring');
var urlLib=require('url');
http.createServer(function(req,res){
    //GET request parsing data
    var obj=urlLib.parse(req.url,true);
    var url=obj.pathname;
    var GET=obj.query;
    //POST request parsing data
    var str='';
    res.on('data',function(data){
        str+=data;
    })
    res.on('end',function(){
        var POST=querystring(str);
    })
    //File request
    var file_name='./www'+url;
    fs.readFile(file_name,function(err,data){
        if(err){
            res.write('404');//File not found return 404
        }else{
            res.write(data);//Find file return file information
        }
        res.end();
    })
}).listen(8080)

The above is the fs module method I have used now, which will be updated later.

Tags: encoding less

Posted on Thu, 02 Apr 2020 18:35:27 -0700 by PHPFreaksMaster