Node.js file Action method Rollup _node.js

Source: Internet
Author: User
Tags readable readfile

Node.js, like any other language, has file operations. First of all, do not say Node.js file operation, other language file operations are generally open, close, read, write, file information, new delete directory, delete files, detection file path. The same is true in Node.js, which is that the API is not quite the same as other languages.

First, synchronous, asynchronous turn off

/**
 * Created by the Administrator on 2016/3/21
 . * *
var fs=require ("FS");
Synchronous Read Fs.opensync = function (path, flags, mode)
//module Fs.js file OpenSync functions as defined above 3 parameters
//.1.path file path
//2. Flags Open File Mode
//3.model Set 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");
    });


The flags are also available in other languages. In fact, mainly divided into 3 parts R, W, A and C in the same.

1.r--opens the file as read-only and the initial location of the data stream begins at the file
2.r+--opens the file in read-write mode, starting at the beginning of the data stream
3.w--If the file exists, the length of the file is 0, that is, the contents of the file are lost. If it does not exist, try creating it. The initial location of the data flow starts at the file
4.w+--opens the file as read-write and if the file does not exist, try to create it and, if it exists, clear the file length by 0, that is, the contents of the file will be lost. The initial location of the data flow starts at the file
5.a--opens the file as write-only, and if the file does not exist, try to create it, the initial position of the data flow is at the end of the file, and each subsequent write operation appends the data to the file.
6.a+--opens the file as read-write, and if the file does not exist, try to create it, the initial position of the data flow is at the end of the file, and each subsequent write operation appends the data to the file.

Ii. Reading and writing

1. Simple file reading and writing

/** * Created by the 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 definition string encoding encoding, mode, flag attribute optional//Asynchronous//fs.writefile = function (path, data, options, Callback_)//Sync
  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_)//Sync//fs.readfilesync = function (path, options) FS.READFI
    Le (' 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.js
Config Saved.
Config Loaded.
Max files:20
Max connections:15
Root Path:/webroot

Process finished with exit code 0

2. Synchronous reading and writing

/** * Created by the 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 written string or buffer//offset is the second parameter begins to read the index null is the number of bytes written to represent the current index//length NULL is written to the end of the data buffer//pos
  ition specifies where to begin writing in the file the current position//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.js wrote
Olives 7bytes
wrote celery 7bytes
wrote carrots 8bytes
read 5bytes
read 5bytes
read 5bytes
Read 5bytes
read 2bytes
read 0bytes
veggies:olives celery carrots     

Process finished with exit code 0

3. Asynchronous read and write and synchronous read and write parameters are almost as much as the callback

/** * Created by the 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, b
      Ytes) {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.js wrote
: Grapes 7bytes
wrote:banana 7bytes
wrote:orange 7bytes
wrote:apple 6bytes
read 5bytes
read 5bytes
Read 5bytes
read 5bytes
read 5bytes
read 2bytes
fruits:grapes banana Orange Apple  

Process Finished with exit code 0

4. Streaming read-write

/** * Created by the Administrator on 2016/3/21.
* * var fs = require (' FS ');
var grains = [' wheat ', ' rice ', ' oats '];
var options = {encoding: ' UTF8 ', flag: ' W '}; From the following system APIs you can see that Createwritestream is creating a writable stream//fs.createwritestream = function (path, options) {//return new Write
Stream (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.");
Flow-type 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 is the creation of 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.js wrote
: Oats 
wrote:rice 
wrote:wheat 
File Closed.
Grains:oats Rice Wheat 
Read bytes of data.
File Closed.

Process finished with exit code 0

Personally feel like these APIs with a feel of the OK, encountered will be used on the line.

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.