Nodejs Copy of study notes

Source: Internet
Author: User

Front-End child shoes are aware that JavaScript is not authorized to manipulate disk files, server children's shoes have always been very despised. But Nodejs let us front-end proud Ah, recently learning node, its powerful features make people excited and excited. Learn how to read and write files today.

The first step is to introduce the FS module, which is Nodejs.

var fs=require ("FS");

Refer to Nodejs Api:http://www.w3cfuns.com/tools.php?mod=booknodejs for details

There are two main methods used:

1. Fs.readfile (filename, [encoding], [callback])

This is the asynchronous read file,filename is the file path,encoding is the encoding format, andcallback is the callback function.

Asynchronously reads all the contents of a file, as in the following example:

function (err, data) {  ifthrow  err;  Console.log (data);});

Here I am using a local test file:

function ReadFile () {    console.log ('--------start reading file--------');     var fs = require (' FS ');    Fs.readfile (the function(err, data)        {if  (err) {            Console.log (" Read failed ");         Else {            console.log (data);             return data;        }    );    Console.log ('--------read end--------');}
2, Fs.writefile (filename, data, encoding= ' UTF8 ', [callback])

Write file:

function WriteFile (data) {    fs.writefile ("Test2.txt", data,function(error) {        if (Error) {            throw  error;        } Else {            console.log ("file Saved");}            }    );

Error code: Copyfile.js file

varFs=require ("FS");functionReadFile () {Console.log ('--------start reading files--------'); varFS = require (' FS '); Fs.readfile (' Test.txt ', ' utf-8 ',function(err, data) {if(Err) {Console.log ("Read Failed"); } Else{console.log (data); returndata;    }    }); Console.log ('--------Read End--------');}functionWriteFile (data) {Fs.writefile ("Test2.txt", data,function(Error) {if(Error) {Throwerror; }Else{Console.log ("File is saved"); }    });}functionCopyFile () {vartxt=ReadFile (); WriteFile (TXT);} CopyFile ();

The result of running node Copyfile.js at the terminal is as follows:

Precautions:

1, the file code, the beginning of the time I directly in the local new TXT document, read the results are always aaaaaaa this, the results found in the editor Open is garbled, second, preferably with encoding, otherwise it will be read in buffer.

2, synchronous execution problem.

The above code is problematic, I write the read file and write the file method separately, Originally wanted to copy the contents of the Test.txt file to Test2.txt, but read the file is executed asynchronously, that is, who does not know what year the horse month execution is complete, so test.txt get the result is undefined.

The correct way to do this is to write the file after the read is completed:

varFs=require ("FS");functionCopyFile () {Console.log ('--------start reading files--------'); varFS = require (' FS '); Fs.readfile (' Test.txt ', ' utf-8 ',function(err, data) {if(Err) {Console.log ("Read Failed"); } Else{WriteFile (data)returndata;    }    }); Console.log ('--------Read End--------');}functionWriteFile (data) {Console.log (data); Fs.writefile ("Test2.txt", data, ' UTF8 ',function(Error) {if(Error) {Throwerror; }Else{Console.log ("File is saved"); }    });} CopyFile ();

Nodejs Copy of study notes

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.