Node. js file operation method summary, node. js Operation Method

Source: Internet
Author: User

Node. js file operation method summary, node. js Operation Method

Like other languages, Node. js also has file operations. Not to mention node. in js, file operations in other languages generally include opening, closing, reading, writing, file information, creating and deleting directories, deleting files, and detecting file paths. The same is true in node. js. These functions are also used, probably because the APIs are not the same as those in other languages.

1. synchronous and asynchronous enabling and disabling

/*** Created by Administrator on 2016/3/21. */var fs = require ("fs"); // synchronize read fs. openSync = function (path, flags, mode) // module fs. in the js file, if the above-defined openSync function has three parameters //. 1. path file path // 2. flags file opening mode // 3. model sets the File Access Mode // fd file description var fd = fs. openSync ("data/openClose.txt", 'w'); // fs. closeSync = function (fd) fs. closeSync (fd); // asynchronous read/write // fs. open = function (path, flags, mode, callback _) // fs. close = function (fd, callback) fs. open ("data/ OpenColse1.txt ", 'w', function (err, fd) {if (! Err) {fs. close (fd, function () {console. log ("closed ");});}});

Among them, flags can also be used in other languages. In fact, it is mainly divided into three parts: r, w, a. and C.

1. r -- open the file in read-only mode. The initial position of the data stream starts at the file.
2. r + -- open the file in read/write mode, and the initial position of the data stream starts at the file
3. w -- if the file exists, the file length is cleared to 0, that is, the file content will be lost. If it does not exist, try to create it. The initial location of the data stream starts with the file.
4. w + -- open the file in read/write mode. If the file does not exist, try to create it. If the file exists, the file length is cleared to 0, indicating that the file content will be lost. The initial location of the data stream starts with the file.
5. a -- open the file in write-only mode. If the file does not exist, create it. The initial position of the data stream is at the end of the file. Data is appended to the end of the file for each subsequent write operation.
6. a + -- open the file in read/write mode. If the file does not exist, create it. The initial position of the data stream is at the end of the file. Data is appended to the end of the file for each subsequent write operation.

Ii. read/write

1. Read and Write simple files

/*** Created by Administrator on 2016/3/21. */var fs = require ('fs'); var config = {maxFiles: 20, maxConnections: 15, rootPath: "/webroot"}; var configTxt = JSON. stringify (config); var options = {encoding: 'utf8', flag: 'W '}; // options defines the encoding, mode, and flag attributes of the mode flag used by string encoding to open the file. Optional // asynchronous // fs. writeFile = function (path, data, options, callback _) // synchronize // fs. writeFileSync = function (path, data, options) fs. writeFile ('data/config.txt ', configTxt, options, function (err) {if (err) {console. log ("Config Write Failed. ");} else {console. log ("Config Saved. "); readFile () ;}}); function readFile () {var fs = require ('fs'); var options = {encoding: 'utf8', flag: 'R'}; // asynchronous // fs. readFile = function (path, options, callback _) // synchronize // fs. readFileSync = function (path, options) fs. readFile ('data/config.txt ', options, function (err, data) {if (err) {console. log ("Failed to open Config File. ");} else {console. log ("Config Loaded. "); var config = JSON. parse (data); console. log ("Max Files:" + config. maxFiles); console. log ("Max Connections:" + config. maxConnections); console. log ("Root Path:" + config. rootPath );}});}
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe SimpleReadWrite.jsConfig Saved.Config Loaded.Max Files: 20Max Connections: 15Root Path: /webrootProcess finished with exit code 0

2. synchronous read/write

/*** Created by Administrator on 2016/3/21. */var fs = require ('fs'); var veggieTray = ['carrots', 'celery ', 'olives']; fd = fs. openSync ('data/veggie.txt ', 'w'); while (veggieTray. length) {veggie = veggieTray. pop () + ""; // system api // fd file description the second parameter is the Written String or Buffer // offset is the index that the second parameter starts to read. null indicates that the current index is written. // length the number of bytes null is always written to the end of the data buffer // position specifies the position where the file starts to be written. The current position of the file // fs. writeSync (fd, buffer, offset, length [, position]); // fs. writeSync (fd, string [, position [, encoding]); // fs. writeSync = function (fd, buffer, offset, length, position) var bytes = fs. writeSync (fd, veggie, null, null); console. log ("Wrote % s % dbytes", veggie, bytes);} fs. closeSync (fd); var fs = require ('fs'); fd = fs. openSync ('data/veggie.txt ', 'R'); var veggies = ""; do {var buf = new Buffer (5); buf. fill (); // fs. readSync = function (fd, buffer, offset, length, position) var bytes = fs. readSync (fd, buf, null, 5); console. log ("read % dbytes", bytes); veggies + = buf. toString () ;}while (bytes> 0); fs. closeSync (fd); console. log ("Veggies:" + veggies );
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe syncReadWrite.jsWrote olives 7bytesWrote celery 7bytesWrote carrots 8bytesread 5bytesread 5bytesread 5bytesread 5bytesread 2bytesread 0bytesVeggies: olives celery carrots     Process finished with exit code 0

3. asynchronous read/write and synchronous read/write parameters are more than callback

/** * Created by Administrator on 2016/3/21. */var fs = require('fs');var fruitBowl = ['apple', 'orange', 'banana', 'grapes'];function writeFruit(fd){  if (fruitBowl.length){    var fruit = fruitBowl.pop() + " ";   // fs.write(fd, buffer, offset, length[, position], callback);   // fs.write(fd, string[, position[, encoding]], callback);   // fs.write = function(fd, buffer, offset, length, position, callback)    fs.write(fd, fruit, null, null, function(err, bytes){      if (err){        console.log("File Write Failed.");      } else {        console.log("Wrote: %s %dbytes", fruit, bytes);        writeFruit(fd);      }    });  } else {    fs.close(fd);    ayncRead();  }}fs.open('data/fruit.txt', 'w', function(err, fd){  writeFruit(fd);});function ayncRead(){  var fs = require('fs');  function readFruit(fd, fruits){    var buf = new Buffer(5);    buf.fill();    //fs.read = function(fd, buffer, offset, length, position, callback)    fs.read(fd, buf, 0, 5, null, function(err, bytes, data){      if ( bytes > 0) {        console.log("read %dbytes", bytes);        fruits += data;        readFruit(fd, fruits);      } else {        fs.close(fd);        console.log ("Fruits: %s", fruits);      }    });  }  fs.open('data/fruit.txt', 'r', function(err, fd){    readFruit(fd, "");  });}
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe asyncReadWrite.jsWrote: grapes 7bytesWrote: banana 7bytesWrote: orange 7bytesWrote: apple 6bytesread 5bytesread 5bytesread 5bytesread 5bytesread 5bytesread 2bytesFruits: grapes banana orange apple  Process finished with exit code 0

4. Stream read/write

/*** Created by Administrator on 2016/3/21. */var fs = require ('fs'); var grains = ['wheel', 'Rice ', 'oats']; var options = {encoding: 'utf8 ', flag: 'W'}; // The following system api shows that createWriteStream creates a writable stream // fs. createWriteStream = function (path, options) {// return new WriteStream (path, options); //}; // util. inherits (WriteStream, Writable); // fs. writeStream = WriteStream; // function WriteStream (path, options) var fileWriteStream = fs. createWriteStream ("data/grains.txt", options); fileWriteStream. on ("close", function () {console. log ("File Closed. "); // streaming read streamRead () ;}); while (grains. length) {var data = grains. pop () + ""; fileWriteStream. write (data); console. log ("Wrote: % s", data);} fileWriteStream. end (); // streaming READ function streamRead () {var fs = require ('fs'); var options = {encoding: 'utf8', flag: 'R '}; // fs. createReadStream = function (path, options) {// return new ReadStream (path, options); //}; // util. inherits (ReadStream, Readable); // fs. readStream = ReadStream; // function ReadStream (path, options) // createReadStream creates a readable stream var fileReadStream = fs. createReadStream ("data/grains.txt", options); fileReadStream. on ('data', function (chunk) {console. log ('grains: % s', chunk); console. log ('read % d bytes of data. ', chunk. length) ;}); fileReadStream. on ("close", function () {console. log ("File Closed. ");});}
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe StreamReadWrite.jsWrote: oats Wrote: rice Wrote: wheat File Closed.Grains: oats rice wheat Read 16 bytes of data.File Closed.Process finished with exit code 0

I personally think it's okay to use these Apis as soon as they are used.

Articles you may be interested in:
  • Nodejs File operation module FS (File System) common functions concise summary
  • Node. js file operations
  • Node. js local file operations-file copying and directory traversal methods
  • Summary of local file operations in Node. js programs

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.