nodejsファイル操作

14844 ワード

****ファイル操作モジュールは、オペレーティングシステム命令の代わりに完全に********できます.
1.****nodejs             。      Sync
    //    
    fs.unlink('/tmp/hello', (err) => {
      if (err) throw err;
      console.log('successfully deleted /tmp/hello');
    });
    //    
    fs.unlinkSync('/tmp/hello');
    console.log('successfully deleted /tmp/hello');

2.**       
    fs.rename('/tmp/hello', '/tmp/world', (err) => {
      if (err) throw err;
      console.log('renamed complete');
    });
    fs.stat('/tmp/world', (err, stats) => {
      if (err) throw err;
      console.log(`stats: ${JSON.stringify(stats)}`);
     //stats: {"dev":-593730986,"mode":33206,"nlink":1,"uid":0,"gid":0,
     //"rdev":0,"ino":2251799813714667,"size":3,"atime":"2016-03-25T07:41:15.892Z",
     //"mtime":"2016-03-25T07:41:19.870Z","ctime":"2016-03-25T07:42:00.065Z",
     //"birthtime":"2016-03-25T07:41:15.819Z"}

    });
    //      
    fs.rename('/tmp/hello', '/tmp/world', (err) => {
      if (err) throw err;
      fs.stat('/tmp/world', (err, stats) => {
        if (err) throw err;
        console.log(`stats: ${JSON.stringify(stats)}`);
      });
    });
     
4.Class: fs.FSWatcher  ,  fs.watch()    
    (1)Event: 'change'
            event        
            filename       
    (2)Event: 'error'
    (3)watcher.close()         

5.Class: fs.ReadStream  
    (1)Event: 'open' fd         
         ReadStream       
    (2)readStream.path        

6.***Class: fs.Stats  
    (1)   fs.stat(), fs.lstat()、 fs.fstat() 
        stats.isFile()
        stats.isDirectory()
        stats.isBlockDevice()
        stats.isCharacterDevice()
        stats.isSymbolicLink() (only valid with fs.lstat())
        stats.isFIFO()
        stats.isSocket()
        //  
            fs.stat('input.txt', function (err, stats) {
           if (err) {
               return console.error(err);
           }
           console.log(stats);
           console.log("        !");
           
           //       
           console.log("     (isFile) ? " + stats.isFile());
           console.log("     (isDirectory) ? " + stats.isDirectory());    
        });
    (2)       util.inspect(stats)   
        {
          dev: 2114,
          ino: 48064969,
          mode: 33188,
          nlink: 1,
          uid: 85,
          gid: 100,
          rdev: 0,
          size: 527,
          blksize: 4096,
          blocks: 8,
          atime: Mon, 10 Oct 2011 23:24:11 GMT, //Access Time"
          mtime: Mon, 10 Oct 2011 23:24:11 GMT, //Modified Time     
          ctime: Mon, 10 Oct 2011 23:24:11 GMT, //Change Time status   
          birthtime: Mon, 10 Oct 2011 23:24:11 GMT //    
        }

7.Class: fs.WriteStream      
    (1)Event: 'open' fd         
         WriteStream       
    (2)writeStream.bytesWritten               
    (3)writeStream.path      

8.fs.access(path[, mode], callback)
    (1)mode  
        fs.F_OK -         ,  ,  rwx  
        fs.R_OK -     
        fs.W_OK -     
        fs.X_OK -          Windows    (will behave like fs.F_OK).
    (2)  
        fs.access('/etc/passwd', fs.R_OK | fs.W_OK, (err) => {
            console.log(err ? 'no access!' : 'can read/write');
        });
    (3)  ,       
        fs.accessSync(path[, mode])

9.***fs.appendFile(file, data[, options], callback)     
    (1)  
        file  |  filename    file descriptor
        data  |    
        options  |  
            encoding  |  default = 'utf8'
            mode  default = 0o666
            flag  default = 'a'
        callback 
    (2)  
        fs.appendFile('message.txt', 'data to append','utf8', (err) => {
          if (err) throw err;
          console.log('The "data to append" was appended to file!');
        });
    (3)    
        fs.appendFileSync(file, data[, options])

10.    ????
    fs.chmod(path, mode, callback)
    fs.chmodSync(path, mode)

    fs.chown(path, uid, gid, callback)#
    fs.chownSync(path, uid, gid)#

11.***    
    fs.close(fd, callback)
    fs.closeSync(fd)
    //  
        var buf = new Buffer(1024);
        console.log("      !");
        fs.open('input.txt', 'r+', function(err, fd) {
           if (err) {
               return console.error(err);
           }
           console.log("      !");
           console.log("      !");
           fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
              if (err){
                 console.log(err);
              }

              //         
              if(bytes > 0){
                 console.log(buf.slice(0, bytes).toString());
              }

              //     
              fs.close(fd, function(err){
                 if (err){
                    console.log(err);
                 } 
                 console.log("      ");
              });
           });
        });

12.****fs.createReadStream(path[, options])   ReadStream  
    (1)options
        {
          flags: 'r',
          encoding: null, 
          fd: null, //    ,   path,       ,   open  
          mode: 0o666,
          autoClose: true, //  false       
          start:Number, //    
          end:Number//    
        }
    (2)fs.createReadStream('sample.txt', {start: 90, end: 99});

     (3)   
        fs.createReadStream = function(path, options) {
           return new ReadStream(path, options);
        };
13.****fs.createWriteStream(path[, options])   WriteStream
    (1)
        {
          flags: 'w',
          defaultEncoding: 'utf8',
          fd: null,
          mode: 0o666,
          autoClose: true
        }
    (2)       
        fs.createWriteStream = function(path, options) { 
          return new WriteStream(path, options);
        };
    (3)  ********
            var fs = require('fs'),
            path = require('path'),
            out = process.stdout;
            var filePath = 'x264-BATV.mkv';

            var readStream = fs.createReadStream(filePath);
            var writeStream = fs.createWriteStream('file.mkv');

            var stat = fs.statSync(filePath);

            var totalSize = stat.size;
            var passedLength = 0;
            var lastSize = 0;
            var startTime = Date.now();

            readStream.on('data', function(chunk) {
                passedLength += chunk.length;//         
                if (writeStream.write(chunk) === false) {
                    readStream.pause();
                }
            });

            readStream.on('end', function() {
                writeStream.end();
            });

            writeStream.on('drain', function() {
                readStream.resume();
            });

            setTimeout(function show() {
                var percent = Math.ceil((passedLength / totalSize) * 100);
                var size = Math.ceil(passedLength / 1000000);
                var diff = size - lastSize;
                lastSize = size;
                out.clearLine();
                out.cursorTo(0);
                out.write('   ' + size + 'MB, ' + percent + '%,   :' + diff * 2 + 'MB/s');
                if (passedLength < totalSize) {
                    setTimeout(show, 500);
                } else {
                    var endTime = Date.now();
                    console.log();
                    console.log('   :' + (endTime - startTime) / 1000 + ' 。');
                }
            }, 500);
14.***    
    fs.mkdir(path[, mode], callback) mode  0o777
    fs.mkdirSync(path[, mode])
    //    
    fs.mkdir('/tmp/test',function(err){
       if (err) {
           return console.error(err);
       }
       console.log("      。");
    });
15.**fs.open(path, flags[, mode], callback)     
    (1)flags
        'r' -    .        
        'r+' -   .        
        'rs'    ,          fs.openSync()
        'rs+'     
        'w' -    .        
        'wx' -    .        
        'w+' -     .            
        'wx+' -     .        
        'a' -   .        
        'ax' -   .        
        'a+' -    .        
        'ax+' -    .        
    (2)mode   0666    
    (3)           (err, fd)
    (4)fs.openSync(path, flags[, mode])     

16.***fs.read(fd, buffer, offset, length, position, callback)
           fd     ,  (err, bytesRead, buffer)
    //  
    fs.open('input.txt', 'r+', function(err, fd) {
           if (err) {
               return console.error(err);
           }
           console.log("      !");
           console.log("      :");
           fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
              if (err){
                 console.log(err);
              }
              console.log(bytes + "       ");
              
              //         
              if(bytes > 0){
                 console.log(buf.slice(0, bytes).toString());
              }
           });
        });

17.***fs.readdir(path, callback)     
    (1)  (err, files)files        
    (2)fs.readdirSync(path)    

    (3)  
        console.log("   /tmp   ");
        fs.readdir("/tmp/",function(err, files){
           if (err) {
               return console.error(err);
           }
           files.forEach( function (file){
               console.log( file );
           });
        });
18.***fs.readFile(file[, options], callback)    
     (1)
        file  |  filename or file descriptor
        options  | 
        encoding  |  default = null
        flag  default = 'r'
        callback 
    (2)  
        fs.readFile('/etc/passwd', 'utf8',(err, data) => {
          if (err) throw err;
          console.log(data);
        });
    (3)fs.readFileSync(file[, options])   
                ,    encoding      ,    buffer
         var source = fs.readFileSync('/path/to/source', {encoding: 'utf8'});
         fs.writeFileSync('/path/to/dest', source);

19. ***     
    fs.rename(oldPath, newPath, callback) callback    err
    fs.renameSync(oldPath, newPath)
20.***    
    fs.rmdir(path, callback)callback    err
    fs.rmdirSync(path)#
    //  
        console.log("       /tmp/test");
        fs.rmdir("/tmp/test",function(err){
           if (err) {
               return console.error(err);
           }
           console.log("   /tmp   ");
           fs.readdir("/tmp/",function(err, files){
              if (err) {
                  return console.error(err);
              }
              files.forEach( function (file){
                  console.log( file );
              });
           });
        });

21.***      
    fs.stat(path, callback)#     (err, stats) 
    fs.statSync(path)   fs.Stats.


20.***    
    fs.truncate(path, len, callback) == fs.ftruncate(path,len,callback)//    
    fs.truncateSync(path, len) 
    (1)  
        var fs = require("fs");
        var buf = new Buffer(1024);

        console.log("      !");
        fs.open('input.txt', 'r+', function(err, fd) {
           if (err) {
               return console.error(err);
           }
           console.log("      !");
           console.log("  10        。");
           
           //     
           fs.ftruncate(fd, 10, function(err){
              if (err){
                 console.log(err);
              } 
              console.log("      。");
              console.log("       "); 
              fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
                 if (err){
                    console.log(err);
                 }

                 //         
                 if(bytes > 0){
                    console.log(buf.slice(0, bytes).toString());
                 }

                 //     
                 fs.close(fd, function(err){
                    if (err){
                       console.log(err);
                    } 
                    console.log("      !");
                 });
              });
           });
        });

21.***fs.unwatchFile(filename[, listener])
     (1)        
          fs.watch(filename[, options][, listener]) 
          options:{ persistent: true, recursive: false }.
          listener:(event, filename)
     (2)  
            fs.watch('somedir', (event, filename) => {
              console.log(`event is: ${event}`);
              if (filename) {
                console.log(`filename provided: ${filename}`);
              } else {
                console.log('filename not provided');
              }
            });
22.***fs.watchFile(filename[, options], listener) 
     //          (                  )
    (1)options:{ persistent: true, interval: 5007 }.
    (2)  
        fs.watchFile('message.text', (curr, prev) => {
          console.log(`the current mtime is: ${curr.mtime}`);
          console.log(`the previous mtime was: ${prev.mtime}`);
        });
        //watch()                  “  ”(       )   
        fs.watch() is more efficient than fs.watchFile

23.***   
    (1)fs.write(fd, data[, position[, encoding]], callback)
    (2)fs.writeFile(file, data[, options], callback)
     (4)    
        fs.writeFileSync(file, data[, options])
        fs.writeSync(fd, buffer, offset, length[, position])
        fs.writeSync(fd, data[, position[, encoding]])

    (5)  ,     
        fs.writeFile('input.txt', '           !',  function(err) {
           if (err) {
               return console.error(err);
           }
           console.log("      !");
           console.log("--------     -------------")
           console.log("       !");
           fs.readFile('input.txt', function (err, data) {
              if (err) {
                 return console.error(err);
              }
              console.log("        : " + data.toString());
           });
        });