Nodejs file System (FS) vs. Stream (Stream)

Source: Internet
Author: User
Tags gz file readfile

First, Introduction

This article describes the node. js file System (FS) and the stream (stream) of some APIs that have been used for parameter usage.

Second, the catalogue

The file system describes the following methods:

1.fs.readfile

2.fs.writefile

3.fs.open

4.fs.read

5.fs.stat

6.fs.close

7.fs.mkdir

8.fs.rmdir

9.fs.readdir

10.fs.unlink

The stream stream has four types of readable,writable,duplex,transform and events for the stream object.

III. Introduction to the main methods of file system FS

1, Fs.readfile

The ReadFile method mainly reads the contents of the file and asynchronously operates.

var fs = require (' FS ') fs.readfile (' a.txt ',function(err,data) {    if (Err) {        return  console.error (err);    } Else {        Console.log ("asynchronous read:" + data.tostring ())}    )

2, Fs.writefile

    WriteFile write files asynchronously, fs. (file, Data[ , Options], Callback)

var fs = require (' FS ') Console.log ("ready to write to file") fs.writefile (' input.txt ', "Write content",  function(err) {    if  (err) {        return  console.error (err);    } Else {        console.log ("write success");}    })

3, Fs.open ()

    Open file in async mode, fs. (path, Flags[,< Span class= "PLN" > Mode], Callback)

var fs = require ("FS"); // asynchronously opens the file console.log ("Ready to open File"); Fs.open (err, FD) {///r+ is opened in read-write mode, FD is the returned file descriptor   if  (err) {       return  console.error (err);   }  Console.log ("File open successfully!") ");     });

4, Fs.read ()

This method reads the file asynchronously, in the format:FS. Read(fd, buffer, offset, length, position, callback)

varFS = require ("FS");varBUF =NewBuffer (1024); Console.log ("Ready to open the file!" "); Fs.open (' At.txt ', ' r+ ',function(Err, FD) {if(err) {returnConsole.error (ERR); } fs.read (FD, buf,0, buf.length, 0,function(err, bytes) {if(Err) {Console.log (err); }      //output only bytes read      if(Bytes > 0) {Console.log (Buf.slice (0, bytes). toString ()); }   });});

5, Fs.stat ()

This method gets the file information asynchronously, in the format:FS. Stat(path, callback)

function (err, stats) {    console.log (Stats.isfile ());          // true})

An instance of the stats class that is returned asynchronously has many methods, such as Stats.isfile () judging whether it is a file, stats.isdirectory () Judging whether it is a directory, ...

6, Fs.close ()

Fs.close () is an asynchronous way to close a file in syntax format:FS. Close(fd, callback) with the following parameters:

d -The file descriptor returned by the Fs.open () method.

Callback -callback function, no parameters.

7, Fs.mkdir ()

This method is created for the directory, format:FS. mkdir(path[, mode], callback), the parameters are as follows:

Path: Paths.

Mode: Directory permissions, default 0777.

Callback: Callback, no parameters.

var fs = require ("FS"), Console.log ("Create directory/test/"), Fs.mkdir ("/test/",function (Err) {   if  (err) {       return  console.error (err);   }   Console.log ("The/test directory was created successfully. ");});

8, Fs.rmdir ()

Delete directory, Syntax format: Fs.rmdir (Path,callback)

9, Fs.readdir ()

This method is read directory, syntax format:FS. Readdir(path, callback), the callback callback function has two parameters, the first is err, and the second is the file array under directory.

var fs = require ("FS"), Console.log ("View/tmp directory"), Fs.readdir ("/tmp/",function (err, files) {   if  (err) {       return  console.error (err);   }    function (file) {       console.log (file);   } );

10, Fs.unlink ()

This method acts as a delete file in the format:FS. Unlink(path, callback)

var fs = require ("FS"); Console.log ("Prepare to delete files! "); Fs.unlink (err   ) {if  (err) {       return  Console.error (err);   }   Console.log ("file deleted successfully! ");});

Iv. stream Type and event description

1, Stream: Stream is an abstract interface, there are four types of flow:

Readable: readable;

Writable: writable operation;

Duplex: readable and writable operation;

Transform: The operation is written to the data and then the result is read.

All stream objects are instances of eventemitter, and common events are:

Data: When there is a readable trigger,

End: No data-readable trigger,

Error: Triggered when a fault occurs,

Finish: The trigger is complete.

2. Read data from the stream

varFS = require ("FS");vardata = ';//to create a readable streamvarReaderstream = Fs.createreadstream (' input.txt '));//set the encoding to UTF8. Readerstream.setencoding (' UTF8 ');//Process Stream Events--data, end, and errorReaderstream.on (' Data ',function(chunk) {data+=Chunk;}); Readerstream.on (' End ',function() {console.log (data);}); Readerstream.on (' Error ',function(Err) {console.log (err.stack);}); Console.log ("Program execution complete");

3. Write stream:

varFS = require ("FS");vardata = ' Write stream data ';//Create a stream that can be written to the file Output.txtvarWriterstream = Fs.createwritestream (' output.txt '));//writing data using UTF8 encodingWriterstream.write (data, ' UTF8 '));//Mark file Endwriterstream.end ();//Process Stream Events--data, end, and errorWriterstream.on (' Finish ',function() {Console.log ("Write complete. ");}); Writerstream.on (' Error ',function(Err) {console.log (err.stack);}); Console.log ("Program execution complete");

4, Pipeline flow (pipe)

var fs = require ("FS"); // Create a readable stream var readerstream = Fs.createreadstream (' input.txt '); // Create a writable stream var writerstream = Fs.createwritestream (' output.txt '); // Pipe Read and write operations // reads the contents of the Input.txt file and writes the contents to the Output.txt file readerstream.pipe (Writerstream); Console.log ("Completion of program execution");

5. Chain-Flow

A chain is a mechanism that flows through the connection output to another stream and creates multiple flow operation chains. Chained streams are typically used for pipeline operations.

Next we are using pipelines and chains to compress and decompress files.

//CompressionvarFS = require ("FS");varZlib = require (' zlib '));//compress input.txt files to input.txt.gzFs.createreadstream (' Input.txt '). Pipe (Zlib.creategzip ()). Pipe (Fs.createwritestream (' Input.txt.gz ')); Console.log (The file compression is complete. ");//UnzipvarFS = require ("FS");varZlib = require (' zlib '));//Unzip the input.txt.gz file to Input.txtFs.createreadstream (' input.txt.gz '). Pipe (Zlib.creategunzip ()). Pipe (Fs.createwritestream (' Input.txt ')); Console.log (The file is unzipped. ");

V. Summary

Nodejs file System (FS) vs. Stream (Stream)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.