General summary of file operations in Node.js _node.js

Source: Internet
Author: User
Tags mkdir posix readfile require file permissions

Objective

Node.js provides a set of UNIX (POSIX) standard file manipulation APIs. The Node import file System module (FS) syntax looks like this:

var fs = require ("FS")

FS module is the encapsulation of file operation, it provides the file read, write, rename, delete, traverse directory, link and other POSIX file system operation. Unlike other modules, all operations in the FS module provide two versions of Asynchrony and synchronization, such as functions that read the contents of a file that are asynchronous fs.readFile() and synchronized fs.readFileSync() .

I. Directory operations

1. Create a table of contents

The syntax for creating a directory is as follows:

Fs.mkdir (path[, mode], callback)//asynchronous Method
Fs.mkdirsync (path[, mode)//sync method

Example:

var fs = require ("FS");

Create the test directory
fs.mkdir (' Test ', function (err) {if (err) {return
  console.error (Err
 ) in the same directory as this file) Console.log ("Directory creation succeeded.) ");
});

2. Reading directory

The syntax for reading the directory is as follows:

Fs.readdir (Path, callback)
Fs.readdirsync (path)

1, Path: file paths;

2, Callback: callback function, callback function with two parameters err, files. Err is the error message and files is a list of file arrays in the directory.

Example:

var fs = require ("FS");

Fs.readdir ("test/", function (err, files) {
 if (err) {return
  console.log (err);
 }
 Files.foreach (function (file) {
  console.log (file);});

3. Delete Directory

The syntax for deleting a directory is as follows:

Fs.rmdir (Path, callback)
Fs.rmdirsync (path)

Example:

var fs = require ("FS");

Fs.rmdir ("Test/ewe", function (err) {
 if (err) {return
  console.log (err);
 }

 Fs.readdir ("/test/", function (err, files) {
  if (err) {return
   console.error (err);
  }
  Files.foreach (function (file) {
   console.log (file);});});

Two. File operation

1. Open the file

The syntax for opening a file is as follows:

Fs.open (path, flags, [mode], [Callback (Err, FD)])

Where path is the path to the file, flags refers to how the file is read, and the mode parameter assigns permissions to the file when the file is created, and the default is 0666. The callback function will pass a file descriptor FD.

The common parameter values of flags are as follows:

The file permissions represented by the mode parameter are specifications for read and access to files in the POSIX operating system, usually represented by a octal number. For example, 0754 means that the permissions of the owner of the file are 7 (read, write, execute), the user rights of the same group are 5 (read, execute), and the permissions of the other users are 4 (read).

Example:

var fs = require (' FS ');

Fs.open ("Test.txt", "W", 0644,function (E,FD) {
 try{
  fs.write (FD, "A-fs!", 0, ' UTF8 ', function (e) {
   Fs.closesync (FD);
  })
 } catch (e) {
  throw e;
 }

});

2. Write to File

The syntax for writing to the file is as follows:

Fs.writefile (file, data[, Options], callback)
Fs.writefilesync (file, data[, Options])

Example:

var fs = require ("FS");

Fs.writefile (' test.txt ', ' Hello world! ', function (err) {
 if (err) {return
  console.log (err);
 }

 Fs.readfile (' Test.txt ', function (err, data) {
  if (err) {return
   console.log (err);
  }
  Console.log ("Read file Data asynchronously:" + data.tostring ());});

3. Read the file

The syntax for reading files is as follows:

Fs.read (fd, buffer, offset, length, position, callback)
Fs.readsync (fd, buffer, offset, length, position)

Fs.readfile (file[, Options], callback)
Fs.readfilesync (file[, Options])

Where, fs.read() and fs.readSync() the parameters are as follows:

fd– the file descriptor returned by the Fs.open () method;

Buffer to write buffer– data;

Write offset of the offset– buffer write;

length– the number of bytes to read from the file;

The starting position of the position– file read, and if the value of position is NULL, it is read from the position of the current file pointer;

callback– callback function, there are three parameters err, Bytesread, Buffer,err is error message, Bytesread indicates the number of bytes read, buffer is the buffers object;

fs.read()The following examples are:

var fs = require (' FS '); 
Fs.open (' Test.txt ', ' R ', function (err, FD) { 
if (err) { 
console.error (err); 
return; 
} 
var buf = new Buffer (8); 
Fs.read (FD, buf, 0, 8, NULL, function (err, bytesread, buffer) { 
if (err) { 
console.error (err); 
return; 
} 
Console.log (' bytesread: ' + bytesread); 
Console.log (buffer); 
}) 
;

fs.readFile()The following examples are:

var fs = require (' FS '); 
Fs.readfile (' Test.txt ', function (err, data) { 
 if (err) { 
  console.log (err); 
 } else { 
  console.log ( Data.tostring ()); 

4. Close the file

The syntax for closing a file is as follows:

Fs.close (FD, callback)
Fs.closesync (FD)

5. Delete Files

The syntax for deleting files is as follows:

Fs.unlink (Path, callback)
Fs.unlinksync (path)

Example:

var fs = require ("FS");

Fs.unlink (' Test.txt ', function (err) {
 if (err) {return
  console.log (err);
 }
 Console.log ("File deletion succeeded!") ");
});

6. Determine if the file exists

The syntax for determining whether a file exists is as follows:

Fs.exists (Path, callback)
Fs.existssync (path)

Example:

var fs = require (' FS ');

Fs.exists (' Test.txt ', function (exists) {
 if (exists) {
  Console.log ("file exists!") ");
 } else {
  Console.log ("file does not exist!") ");
 }
});

7. Append content to File

Fs.appendfile (file, data[, Options], callback)
Fs.appendfilesync (file, data[, Options])

Example:

var fs = require (' FS ');

Fs.appendfile ("Test.txt", "Append Content", function (err) {
 if (err) {
  console.log (err);
 } else {
  fs.readfile (' Test.txt ', function (err, data) { 
   if (err) { 
    console.log (err); 
   } else { 
    Console.log (Data.tostring ());}} 
  ); 
 }}
;

Summarize

More file system operations can view the Node.js FS module of the official API documentation, the above is about the general operation of Node.js files, I hope this article for everyone to learn or use Node.js can help, if you have questions you can message exchange.

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.