Read and write files with node.js

node.js no binary data type, but provides "flow" data type byte array similar, with a data type frequently appear in the file system module

  • Open the file node.js
= the require FS ( ' FS ' ); 
the console.log ( ' ready to open the file ' ); 
fs.open ( ' / etc / the hosts ' , ' R & lt + ' , function (ERR, FD) {
     IF (ERR) 
    { 
        the console.log ( ' Damn open error ~ ' ); 
    } 
    the console.log ( ' can open ' ); 
    fs.Close (FD, function (ERR) { 
        IF (ERR) 
        { 
            console.error (ERR) 
        } 
        the console.log ( ' smoothly off ')
    });
});
  • The contents of the file read into the buffer, and the contents of the buffer read as utf8 mode (hexadecimal can also be oh)
= the require FS ( 'FS'); 
fs.open ( '/ etc / the hosts', 'R & lt +', function (ERR, FD) {
var = mybuffer Buffer.alloc (1024);
offset = 0;
len = mybuffer.length ;
FilePosition = null;
fs.read (FD, mybuffer, offset, len, FilePosition, function (ERR, the readByte) {
the console.log ( "the number of read data may be" the readByte +);
var wuwa mybuffer.slice = (0, the readByte);
the console.log ( "buffer contents prior Interpretation:", wuwa);
the console.log ( "buffer contents Interpretation:", wuwa.toString ( 'UTF8'));
});
});

Output:

196 can read the number of data 
buffer contents prior to interpretation: <Buffer 31 is  32  37 [ 2E 30 2E 30 2E 31 is  20 is  20 is  20 is 6C 6F 63 is  61 is 6C 68 6F 73 is  74  20 is 6C 6F 63 is  61 is 6C 68 6F 73 is  74 2E 6C 6F 63 is  61 is 6C 64 6F 6D 61 is  69 6E 20 is 6C 6F 63 is  61 is 6C 68 ... 146 More bytes> 
the contents of the buffer Interpretation:127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4 coldspring.net taizhouwu.net mydb.net
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
  • Asynchronous read (data still buffer)
= the require FS ( ' FS ' ); 
fs.readFile ( ' / etc / the hosts ' , function (ERR, Data) {
     IF (ERR) 
    { 
        console.error (ERR); 
    } 
    the console.log (data.toString ( ' UTF8 ' )); # still buffer type, type needs to be converted to utf8 
});

Output:

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

 

Guess you like

Origin www.cnblogs.com/saintdingspage/p/11408535.html