Nodejs File System

Source: Internet
Author: User

Nodejs Accessing the file systemAll file system calls need to load the FS module, i.e. var fs=require (' FS '); Nodejs provides nearly all of the functions of the FS module are selected in two forms: asynchronous and synchronous, such as asynchronous write () and synchronous Writesync ()1. Open and close FilesOpen File:
Fs.open (Path,flags,[mode],callback) Fs.opensync (Path,flags,[mode])
Where the path parameter specifies a standard path string for the file system, the flags parameter specifies the mode of the open file, such as read, write, append, and so on, the optional mode parameter sets the file access mode, which defaults to 0666, which indicates readable and writable. To close a file:
Fs.close (fd,callback) Fs.closesync (FD)
An example of a simple asynchronous pattern to open and close a file
Fs.open (' MyFile ', ' w ',function(ERR,FD) {    if(!  Error) {        fs.close (FD);    }}

Note: The callback function is specified and receives the ERR and FD parameters, which are file descriptors that you can use to read or write to the file.

2. Writing FilesThe FS module provides four ways to write data to a file (1) to write to a simple file:
Fs.writefile (Path,data,[options],callback) Fs.writefilesync (Path,data,[options])
Where the path parameter specifies the file's pathname, which can be a relative or absolute path, the data parameter specifies the string or buffer object to be written to the file, and the optional options parameter is an object that can contain the definition string encoding, And a simple example of the Encoding,mode and flag attributes of the pattern and flags used when opening a file:
varFs=require (' FS ');varconfig={maxfiles:20, MaxConnections:15, RootPath:'./routes '};varconfigtxt=json.stringify (config);varoptions={encoding:' UTF8 ', flag:' W '};fs.writefile (' Config.text ', configtxt,options,function(err) {if(Err) {Console.log (' Config write fail '); } Else{Console.log (' Config write success '); }});

(2) Synchronous and asynchronous file writes

Fs.writesync (fd,data,offset,length,position) fs.write (fd,data,offset,length,position,callback)
Where the FD parameter is the file descriptor returned by OpenSync () or open (), the data parameter specifies the string or buffer object to be written to the file, and the offset parameter specifies the index to start reading in the data parameter, if you want to start from the current index of the string or buffer. This value should be null. The lenght parameter specifies the number of bytes to write, and you can specify NULL to indicate that the data buffer has been written to the end. Give an example of an asynchronous write file:
varFs=require (' FS ');varfruitbow1=[' Apple ', ' orange ', ' banana '];functionWritefruit (FD) {if(fruitbow1.length) {varFruit=fruitbow1.pop () + "; Fs.write (Fd,fruit,NULL,NULL,function(err,bytes) {if(Err) {Console.log (' File write failed. '); }Else{Console.log (' Write:%s%dbytes ', fruit,bytes);   Writefruit (FD); //repeated calls until the length of the FruitBow1 is 0            }        }); }Else{fs.close (FD); }}fs.open (' Fruit.txt ', ' W ',function(ERR,FD) {writefruit (FD);});

(3) stream file write to a file to write a large amount of data is, one of the best way is to use the stream, which includes the file as a writeable stream open, writeable flow is easy to implement, you can use the pipe () method with readable stream link, This also makes it easy to write data from readable streams (such as HTTP requests). To asynchronously transfer data to a file, you first need to create a writeable object:
Fs.createwritestream (Path,[options])
Where the path parameter specifies the file's pathname, which can be a relative or absolute path, the optional options parameter is an object that can contain the Encoding,mode and flag attributes that define the string encoding and the use of patterns and flags when the file is opened. Once the writeable file stream is opened, it can be written using the standard streaming write (buffer) method.
var fs=require (' FS '); var grains=[' wheat ', ' rice ', ' oats '; var options={encoding: ' UTF8 ', flag: ' W '}; var filewritestream=fs.createwritestream (' Grains.txt ', Options); Filewritestream.on (' close ', function () {    console.log (' file closed. ') );});  while (grains.length) {    var data=grains.pop () + ';    Filewritestream.write (data);    Console.log (' write:%s ', data);} Filewritestream.end ();

three read filesThe FS module provides four different ways to read data from a file. (1) Simple file read:
Fs.readfile (Path,[options],callback) Fs.readfilesync (Path,[options])
Where the path parameter specifies the file's pathname, which can be a relative or absolute path, the optional options parameter is an object that can contain the Encoding,mode and flag attributes that define the string encoding and the use of patterns and flags when the file is opened. As an example:
varFs=require (' FS ');varoptions={encoding: ' UTF8 ', flag: ' R '};fs.readfile (' Config.txt ', options,function(err,data) {if(Err) {Console.log (' Failes to open config File. '); }Else{Console.log (' Config Loaded. '); varconfig=json.parse (data); Console.log (' Max Files: ' +config.maxfiles); Console.log (' MaxConnections: ' +config.maxconnections); Console.log (' RootPath: ' +Config.rootpath); }});

(2) Synchronous file read
Fs.readsync (fd,buffer,offset,length,position)
(3) Asynchronous file read
Fs.read (D,buffer,offset,length,position,callback)
(4) streaming file read First, create a readable stream object using the following syntax: Fs.createreadstream (Path,[options])
var fs=require (' FS '); var options={encoding: ' UTF8 ', flag: ' R '}; var filereadstream=fs.createreadstream (' 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. ') );});

Nodejs File System

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.