Node. js: FS file module _ node. js

Source: Internet
Author: User
Tags readfile
During the introduction to nodejs, nodejs focuses on its asynchronous IO. In the fs module, nodejs provides two read/write modes: asynchronous and synchronous. I. opening analysis

The file system module is a simple packaged standard POSIX file I/O operation method set. You can obtain this module by calling require ("fs. All methods in the file system module have asynchronous and synchronous versions.

(1) The asynchronous method in the file system module requires a callback function at completion as the last input parameter.

(2) the composition of the callback function is determined by the asynchronous method called. Generally, the first parameter of the callback function is the returned error message.

(3) if the asynchronous operation is executed correctly and the result is returned, the error parameter is null or undefined. If you use a synchronous version operation method, an error will be returned in the form of a common error.

(4) you can use try and catch statements to intercept errors and continue the program.

Let's take a look at a simple example to read the file ("bb.txt "):

(1) create the file "bb.txt", as shown in the following figure ("Hello everyone, I am a great hero! (* ^__ ^ *) Xi ...... ").

(2) read the file using the following code:

The code is as follows:


Var fs = require ("fs ");
Fs. readFile ("bb.txt", "utf8", function (error, data ){
If (error) throw error;
Console. log (data );
});

Running result:

Note that encoding must be set for reading files; otherwise, the format appears in the buffer format by default.

Then let's look at the unconfigured running effect. The difference is quite obvious. As follows:

Another write operation is as follows:

The code is as follows:


Var fs = require ("fs ");
Var txt = "everyone has to learn about NodeJS !!! ";
// Write a file
Fs. writeFile ("bb.txt", txt, function (err ){
If (err) throw err;
Console. log ("File Saved! "); // The file is saved.
});

Running result:

List some common instances:

The code is as follows:


// Delete an object
Fs.unlink('bb.txt ', function (){
Console. log ('success ');
});
// Modify the file name
Fs.rename('bb.txt', 'bigbear.txt ', function (err ){
Console. log ('Rename success ');
});
// View the file status
Fs.stat('bb.txt ', function (err, stat ){
Console. log (stat );
});
// Determine whether a file exists
Fs.exists('bb.txt ', function (exists ){
Console. log (exists );
});

2. relationship between Fs and Stream

"Stream" is asynchronous. I can divide a file or segment into "chunk" of unknown size for reading. every time I read a "chunk", we will output it. Until the file is read. This is like "Transfer-Encoding: chunked" supported by "http1.1. ("Chunk" can exist in any form. by default, NodeJS exists in the form of "Buffer", which is more efficient ). "Stream" in NodeJS has a super feature on Unix systems ("pipe" ------ pipeline ).

Remember the first NodeJS program in "Http module", "Hello, Big Bear! ? Let's make some modifications based on that small program. The following code:

(1), create bb.html"

The code is as follows:







Hello, Big Bear!




(2) before modification, the program is as follows:

The code is as follows:


Var http = require ('http ');
Var fs = require ("fs ");
Var server = http. createServer (function (req, res ){
Fs. readFile ("bb.html", "UTF-8", function (err, data ){
If (err ){
Res. writeHead (500, {'context-type': 'Text/plain '});
Res. end ('specify file not exists! Or server error! ');
}
Else {
Res. writeHead (200, {'context-type': 'Text/html '});
Res. write (data );
Res. end ();
}
})
});
Server. listen (8888 );
Console. log ("http server running on port 8888 ...");

The running result is as follows:

Now we need to think about it. if we want to send a file that is not a simple text file but a hypermedia file, for example, a full HD video file at Google 2014 IO conference. Mp4 format. The length is 2 + hours and 1080 p.

About 4 GB. It is known that "readFile" is used to read files to the memory. This is obviously not the case for such a large file. What should we do? Yes, you need to use stream. This is the case.

The code is as follows:

The code is as follows:


Fs. createReadStream (_ dirname + '/vedio.mp4'). pipe (res );

Summary:

These codes can implement the required functions, but the service needs to cache the entire file data to the memory before sending the file data. if the "bb.html" file is very
If the concurrency is large, a lot of memory will be wasted. Because the user needs to wait until the entire file is cached in the memory to accept the file data, this causes
The user experience is quite poor. But fortunately, "(req, res)" both parameters are Stream, so we can use fs. createReadStream () instead of "fs. readFile ()".

III. instances

To upload a file:

(1) create "server. js"

The code is as follows:


Var http = require ('http ');
Var url = require ('URL ');
Function start (route, handler ){
Function onRequest (request, response ){
Var pathname = url. parse (request. url). pathname;
// Route to the corresponding business logic
Route (pathname, handler, response, request );
}
Http. createServer (onRequest). listen (3000 );
Console. log ('server is starting ');
}
Exports. start = start;

(2) create "route. js"

The code is as follows:


Function route (pathname, handler, response, request ){
Console. log ('about to route a request for '+ pathname );
If (typeof handler [pathname] === 'function '){
Return handler [pathname] (response, request );
} Else {
Console. log ('No request handler found for '+ pathname );
Response. writeHead (404, {'content-type': 'Text/html '});
Response. write ('2014 Not Found! ');
Response. end ();
}
}
Exports. route = route;

(3) Create "requestHandler. js"

The code is as follows:


Var querystring = require ('querystring '),
Fs = require ('Fs '),
Formidable = require ('formidable ');
Function start (response, request ){
Console. log ('Start module ');
Var body =''+
''+
' 'Content = "text/html; charset = UTF-8"/> '+
''+
''+
''+
''+
'';
Response. writeHead (200, {'content-type': 'Text/html '});
Response. write (body );
Response. end ();
}
Function upload (response, request ){
Console. log ('upload module ');
Var form = new formidable. IncomingForm ();
Form. parse (request, function (error, fields, files ){
Fs. renameSync (files. upload. path, '/tmp/test.png ');
Response. writeHead (200, {'content-type': 'Text/html '});
Response. write ('You \ 've sent:
');
Response. write ('');
Response. end ();
});
}
Function show (response, request ){
Console. log ('Show module ');
Fs. readFile ('/tmp/test.png', 'binary ', function (error, file ){
If (error ){
Response. writeHead (200, {'content-type': 'Text/html '});
Response. write (error );
Response. end ();
} Else {
Response. writeHead (200, {'content-type': 'image/png '});
Response. write (file, 'binary ');
Response. end ();
}
});
}
Exports. start = start;
Exports. upload = upload;
Exports. show = show;

(4) Create "index. js"

The code is as follows:


Var server = require ('./server ');
Var router = require ('./router ');
Var requestHandler = require ('./requesthandler ');
Var formidable = require ('formidable'); // require path search algorithm ??
Var handler = {};
Handler ['/'] = requestHandler. start;
Handler ['/start'] = requestHandler. start;
Handler ['/upload'] = requestHandler. upload;
Handler ['/show'] = requestHandler. show;
Server. start (router. route, handler );

IV. Summary

(1) understand the relationship between Fs and Stream ".
(2) familiar with APIs related to "FS.
(3) pay attention to the control of details, such as the processing details between the file operation api synchronization method and the asynchronous method.
(4) Finally, emphasize: understand the code organization method in the file upload example, rebuild and summarize the code.

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.