Nodejs Learning Notes FS file module _node.js

Source: Internet
Author: User
Tags file upload readfile

First, the opening analysis

The file system module is a simple packaged standard POSIX file I/O operation method Set. You can get the module by calling require ("FS"). All methods in the file system module have asynchronous and synchronized versions.

(1), the asynchronous method in the file system module requires a complete callback function as the last incoming parameter.

(2) The composition of the callback function is determined by the calling asynchronous method, which is typically the first parameter of the callback function as the error message returned.

(3) If the asynchronous operation executes correctly and returns, the error parameter is null or undefined. If you are using a synchronized version of the action method, an error is returned in the form of a normal throw error.

(4), you can use statements such as try and catch to intercept an error and keep the program going.

Let's look at a simple example, read the file ("Bb.txt"):

(1), establish the document "Bb.txt", the following content ("Everyone good, I am Shongjun!") (*^__^*) Xi hee ... ").

(2), read the file to operate the following code:

Copy Code code as follows:

var fs = require ("FS");
Fs.readfile ("Bb.txt", "UTF8", function (Error,data) {
if (error) throw error;
Console.log (data);
}) ;

Run Result:

Here to note that: Read the file must set the encoding, otherwise the default is "buffer" form appears.

Again see not set the operation effect, the difference is still very obvious. As follows:

One more write operation, as follows:

Copy Code code as follows:

var fs = require ("FS");
var txt = "Everybody should study well Nodejs!!!" " ;
Write to File
Fs.writefile ("Bb.txt", txt,function (Err) {
if (err) throw err;
Console.log ("File Saved!"); File is saved
}) ;

Run Result:

In the list of some common examples:

Copy Code code as follows:

deleting files
Fs.unlink (' Bb.txt ', function () {
Console.log (' success ');
}) ;
Modify file name
Fs.rename (' Bb.txt ', ' bigbear.txt ', function (err) {
Console.log (' rename success ');
});
View file status
Fs.stat (' Bb.txt ', function (err, stat) {
Console.log (STAT);
});
To determine whether a file exists
Fs.exists (' Bb.txt ', function (exists) {
Console.log (exists);
}) ;

Second, the link between FS and stream

"Stream" has an asynchronous attribute. I can read a file or a piece of content into a "chunk" of unknown size, and we will output it every time a "chunk" is read. Until the file is read. It's like the "http1.1" kind of "transfer-encoding:chunked" support. ("Chunk" can exist in any form, Nodejs by default in the form of "Buffer", which is more efficient). The "Stream" in Nodejs has a Super feature on UNIX systems ("pipe"------pipeline).

Remember the "HTTP module," The first Nodejs program, "Hello, Big Bear!" "?" she said. We made the change based on that small program, the following code:

(1), establish "bb.html"

Copy Code code as follows:



<html>


<head>


<style type= "Text/css" >


div {


margin-top:50px;


width:100%;


margin:0px;


height:120px;


line-height:120px;


Color: #fff;


font-size:22px;


Background: #ff9900;


Text-align:center;


}


</style>


</head>


<body>


<div>hello, Big Bear! </div>


</body>


</html>


(2) The procedure before the modification is as follows:

Copy Code code 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 ({' Context-type ': ' Text/plain '});


Res.end (' Specify File not exists! or Server error! ');


}


else{


Res.writehead ({' Context-type ': ' text/html '});


Res.write (data);


Res.end ();


}


})


}) ;


Server.listen (8888);


Console.log ("HTTP server running on port 8888 ...");


The following are the results of the operation:

Now we need to think about if we're not sending a simple text file but rather a hypermedia file, such as a Google 2014 IO conference Full HD video file. MP4 format. Length 2 hours 1080p.

About 4 gigabytes. Known as "ReadFile" works by reading files to memory. So a file of this size obviously can't do that. So what should we do? After that, you need to use the stream to do it. So that's it.

The code looks like this:

Copy Code code as follows:

Fs.createreadstream (__dirname + '/vedio.mp4 '). pipe (RES);

To sum up:

The code can implement the required functionality, but the service needs to cache the entire file data to memory before sending the file data, if the "bb.html" file is
Large and with a large amount of concurrency, it will waste a lot of memory. Because the user needs to wait until the entire file is cached to memory to accept the file data, which causes
The user experience is rather bad. But fortunately "(req, res)" two parameters are stream, so we can use Fs.createreadstream () instead of "Fs.readfile ()".

Third, the example

To a file to upload the little chestnuts:

(1), establish "Server.js"

Copy Code code 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;
Routing to the appropriate business logic
Route (pathname, handler, response, request);
}
Http.createserver (ONrequest). Listen (3000);
Console.log (' server is starting ');
}
Exports.start = start;

(2), establish "Route.js"

Copy Code code 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 (' 404 Not found! ');
Response.End ();
}
}
Exports.route = route;

(3), establish "Requesthandler.js"

Copy Code code as follows:



var querystring = require (' querystring '),


FS = require (' FS '),


Formidable = require (' formidable ');


function start (response, request) {


Console.log (' Start module ');


var body = ' <html> ' +


' <head> ' +


' <meta http-equiv= ' content-type ' +


' Content= ' text/html; Charset=utf-8 "/> ' +


' </head> ' +


' <body> ' +


' <form action= '/upload ' enctype= ' multipart/form-data ' method= ' post ' > ' +


' <input type= ' file ' name= ' upload ' multiple= ' multiple ' > ' +


' <input type= ' submit ' value= ' submit text '/> ' +


' </form> ' +


' </body> ' +


' </html> ';


Response.writehead ({' 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 ({' Content-type ': ' text/html '});


Response.Write (' you\ ' ve sent: <br/> ');


Response.Write (' <img src= '/show '/> ');


Response.End ();


});


}


Function Show (response, request) {


Console.log (' show module ');


Fs.readfile ('/tmp/test.png ', ' binary ', function (error, file) {


if (Error) {


Response.writehead ({' Content-type ': ' text/html '});


Response.Write (Error);


Response.End ();


} else {


Response.writehead ({' Content-type ': ' Image/png '});


Response.Write (file, ' binary ');


Response.End ();


}


});


}


Exports.start = start;


Exports.upload = upload;


Exports.show= Show;


(4), establish "Index.js"

Copy Code code 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);

Four, sum up

(1) To understand "the link between FS and stream".
(2) Proficiency in the use of "FS" related APIs.
(3), attention to the details of the control, such as: File Operation API synchronization and asynchronous way between the processing details.
(4), finally stressed: understand the file upload examples of code organization, and constantly refactoring, and constantly summarized.

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.