Learn the file operation of node. js from zero (3)

  • 2021-07-22 08:42:24
  • OfStack

1. File manipulation

In the file operation, there are mainly file reading and writing, creating and moving files, etc.

1.1 Reading Files

When reading text files, such as. txt,. js,. json and so on, you can get the contents of the files directly by using readFile.


// server.js
var fs = require('fs');

fs.readFile('./data.txt', 'utf-8', function(err, data){
 if(err) throw err;
 console.log(data);
});

When reading pictures, we can't output them directly to the console, but we need to create a server and view them in the browser. In fact, in the previous section, we have already learned about the process of displaying pictures.


// server.js
var http = require('http'),
 fs = require('fs');

http.createServer(function(request, response){
 //  Use 2 Read pictures in binary mode 
 fs.readFile('./img/test.png', 'binary', function(err, file){
  if( err ) throw err;
  //  The current data is in image/png Output in the mode 
  response.writeHead(200, {"Content-Type": "image/png"});
  response.write(file, 'binary');
  response.end();
 });
}).listen(3000);
console.log('server has started...');

Open the browser: 127.0. 0.1: 3000, and you can see the picture.

1.2 Write to File

Writing a string to a file file is a very simple operation, using writeFile It can be done:


var fs = require('fs');

var data = ' From 1 At the beginning, I chose to do front-end development, because I think front-end development is closer to users, can listen to users' voices, and is more fun, more interesting and more intuitive. We are always trying the latest technology, trying more dazzling effects, hoping to optimize the user experience effect! ';

fs.writeFile('./test.txt', data, function(err){
 if(err) throw err;
 console.log(' Write data successfully ...');
});

writeFile Method, when there is no file, it will create a file and write it; If the file exists, the contents are overwritten.

1.3 Create or rename a file

According to writeFile You can use the writeFile Create a file by writing an empty string.

At the same time, fs.open You can also create files:


//  Open mode can be used  w | w+ | a | a+
//  These modes create files when they open files that do not exist 
// fd For 1 Integer representing the file descriptor returned by opening the file, window Also known as file handle in 
fs.open(Date.now()+'.txt', 'a+', function(err, fd){
 if(err) throw err;
 console.log(fd);
})

In the file system, there is 1 fs.rename As the name implies, rename the file (folder).


fs.rename(oldname, newname, callback(err));

Characteristics:

Move the oldname file (directory) to the path of newname and rename it; If oldname and newname are the same path, rename them directly.

2. Folder action

Usually, the operation of the directory is simpler.

2.1 Read the list of files and folders in a folder

Use fs.readdir(path, callback) You can get the list of files and directories under the path path, and you can only read the files and folders under the direct directory, but you can't get the files in the subdirectory.


fs.readdir('./', function(err, files){
 if(err) throw err;
 console.log( files );
});

Output:


[
 'img',
 'msg.txt',
 'node_modules',
 'package.json',
 'server.js',
 'test.js',
 'tmp'
]

node_modules And tmp Is a folder, the rest is a file, and it can't be obtained node_modules And tmp The data inside. Get all the files in 1 directory, which will be explained later. Wait a moment.

2.2 Delete Folders

Use fs.rmdir(path, callback) Folders can be deleted, but only empty folders can be deleted. If the current path is not a folder or the current folder is not empty, the deletion fails; When the deleted folder is empty, it can be deleted successfully.


fs.rmdir('./tmp', function(err){
 if(err){
  console.log(' Failed to delete folder ');
  throw err;
 }else{
  console.log(' Delete succeeded ');
 }
})

How to delete a directory that is not empty will be explained later, just a moment.

2.3 Getting File or Folder Information

fs. stat (path, callback) can obtain the information of path path, such as creation time, modification time, file size, whether it is a file at present, whether it is a folder at present, etc. If the path path does not exist, an exception is thrown.


fs.stat('./test.js', function(err, stats){
 if( err ){
 console.log( ' Path error ' );
 throw err;
 }
 console.log(stats);
 console.log( 'isfile: '+stats.isFile() ); //  Whether it is a file or not 
 console.log( 'isdir: '+stats.isDirectory() ); //  Is it a folder 
});

Results:


{
 dev: -29606086,
 mode: 33206,
 nlink: 1,
 uid: 0,
 gid: 0,
 rdev: 0,
 blksize: undefined,
 ino: 2251799813687343,
 size: 2063, // path When the path is a folder, size For 0
 blocks: undefined,
 atime: Thu Jan 12 2017 21:12:36 GMT+0800 ( China Standard Time ),
 mtime: Sat Jan 14 2017 21:57:26 GMT+0800 ( China Standard Time ),
 ctime: Sat Jan 14 2017 21:57:26 GMT+0800 ( China Standard Time ),
 birthtime: Thu Jan 12 2017 21:12:36 GMT+0800 ( China Standard Time )
}
isfile: true //  Whether it is a file or not 
isdir: false //  Is it a folder 

For the understanding of these time attributes, you can refer to this article.

The size attribute in stats is the size of the current file (in bytes, divided by 1024 to be kb), and stats also has the following methods available:

stats.isFile() stats.isDirectory() stats.isBlockDevice() stats.isCharacterDevice() stats.isSymbolicLink() (only valid with fs.lstat()) stats.isFIFO() stats.isSocket()

fs.stat(path, callback) Is executed asynchronously, corresponding to the synchronous execution version: fs.statSync(path) This method returns the fs.stats Instance.

3. Comprehensive application

In the above explanation, there are still two functions that have not been realized. Here, the process of realizing it is 1.

3.1 Traverse all the files in the directory

We already know that using readdir can only get the names of files and folders in the current directory. In order to get all the names of files in this directory, we can only read the files in all folders in the current directory. Here we use a recursive method, if the current resource is a file, then store, is a folder, then recursively retrieve one step until all the folders traversed.


// server.js
var http = require('http'),
 fs = require('fs');

http.createServer(function(request, response){
 //  Use 2 Read pictures in binary mode 
 fs.readFile('./img/test.png', 'binary', function(err, file){
  if( err ) throw err;
  //  The current data is in image/png Output in the mode 
  response.writeHead(200, {"Content-Type": "image/png"});
  response.write(file, 'binary');
  response.end();
 });
}).listen(3000);
console.log('server has started...');
0

Use this program to get all the files in the current directory (some files are shown):


// server.js
var http = require('http'),
 fs = require('fs');

http.createServer(function(request, response){
 //  Use 2 Read pictures in binary mode 
 fs.readFile('./img/test.png', 'binary', function(err, file){
  if( err ) throw err;
  //  The current data is in image/png Output in the mode 
  response.writeHead(200, {"Content-Type": "image/png"});
  response.write(file, 'binary');
  response.end();
 });
}).listen(3000);
console.log('server has started...');
1

If you want to output a tree structure, you can modify the current recursive program. For example, if I want to output the following results, then we must analyze the characteristics of this structure:


// server.js
var http = require('http'),
 fs = require('fs');

http.createServer(function(request, response){
 //  Use 2 Read pictures in binary mode 
 fs.readFile('./img/test.png', 'binary', function(err, file){
  if( err ) throw err;
  //  The current data is in image/png Output in the mode 
  response.writeHead(200, {"Content-Type": "image/png"});
  response.write(file, 'binary');
  response.end();
 });
}).listen(3000);
console.log('server has started...');
2

The law that can be seen:

Level 1 files and folders are preceded by no spaces or characters; Files or folders in level 1 subdirectories are preceded by 1 set of spaces and 1 character; Files or folders in level 2 subdirectories are preceded by 2 sets of spaces and 1 character; And so on …

We can pass another depth to represent the level of the current directory, and then calculate the number of spaces in front:


// depth Is the recursive depth, and the format before the file name can be output according to the recursive depth 
function readDirAll(path, depth){
 //  Get String 
 var getLastCode = function(str){
  return str.substr(str.length-1, 1);
 }

 depth = depth || 0; //  Default to 0
 var fir_code = '';

 //  Calculates the characters before the file name, 4 Spaces are 1 Group 
 for(var j=0; j<depth; j++){
  fir_code += ' ';
 }
 depth && (fir_code += '|---');

 var stats = fs.statSync(path);
 if( stats.isFile() ){
  console.log( fir_code+path );
 }else if( stats.isDirectory() ){
  var files = fs.readdirSync(path);
  for(var i=0, len=files.length; i<len; i++){
   var item = files[i],
    itempath = getLastCode(path)=='/' ? path+item : path+'/'+item,
    st = fs.statSync(itempath);

   console.log( fir_code+item );
   if( st.isDirectory() ){
    var s = readDirAll( itempath, depth+1 );
   }
  }
 }
}
console.log( readDirAll('./') ); 

3.2 Delete Directory

Use fs.rmdir(path) Is limited, can only delete empty directory, if it is a non-empty directory, we can write out one can delete all the files under the current directory according to the above ideas. Recursive, as long as find inside the folder recursive search, until find the bottom, the bottom of the file deleted, and then step by step up to delete the folder, until deleted to the current directory.


// server.js
var http = require('http'),
 fs = require('fs');

http.createServer(function(request, response){
 //  Use 2 Read pictures in binary mode 
 fs.readFile('./img/test.png', 'binary', function(err, file){
  if( err ) throw err;
  //  The current data is in image/png Output in the mode 
  response.writeHead(200, {"Content-Type": "image/png"});
  response.write(file, 'binary');
  response.end();
 });
}).listen(3000);
console.log('server has started...');
4

Then the output information when deleting is as follows: first delete the internal files and folders clean, and finally delete './img':


// server.js
var http = require('http'),
 fs = require('fs');

http.createServer(function(request, response){
 //  Use 2 Read pictures in binary mode 
 fs.readFile('./img/test.png', 'binary', function(err, file){
  if( err ) throw err;
  //  The current data is in image/png Output in the mode 
  response.writeHead(200, {"Content-Type": "image/png"});
  response.write(file, 'binary');
  response.end();
 });
}).listen(3000);
console.log('server has started...');
5

Of course, you can also try to implement such a program:

Delete all the contents inside path, and keep the path directory at the same time Delete only files and leave all empty folders Move all internal files to the root directory of path and delete empty folders

And so on, you can try to achieve 1.

Summarize

The above is the whole content of this article. In fact, there are a lot of contents to learn in the file system. Here, I just throw a brick to attract jade. I hope that through my meager knowledge of 1 point, I can give you guidance. This site will continue to share about node introductory learning articles, interested friends please continue to pay attention to this site.


Related articles: