Analysis on Node. js string search function _ node. js-js tutorial

Source: Internet
Author: User
I needed a problem when I was working on the project today. I wanted to find a string, but I forgot it. It was in that file, so I remembered node. js, finding this string without any pressure, shares with you the following requirements:

The entire directory is about 40 MB, and there are countless files. For a long time, I cannot tell which file the character string belongs. Powerful and eye-catching Node. js Debut:

There is no difference between installing Node. js in windows and installing common software. After installation, open the Node. js shortcut, or directly run cmd, you know.

Create findString. js

var path = require("path");var fs = require("fs");var filePath = process.argv[2];var lookingForString = process.argv[3];recursiveReadFile(filePath);function recursiveReadFile(fileName){if(!fs.existsSync(fileName)) return;if(isFile(fileName)){check(fileName);}if(isDirectory(fileName)){var files = fs.readdirSync(fileName);files.forEach(function(val,key){var temp = path.join(fileName,val);if(isDirectory(temp)) recursiveReadFile(temp);if (isFile(temp)) check(temp);})}}function check(fileName){var data = readFile(fileName);var exc = new RegExp(lookingForString);if(exc.test(data))console.log(fileName);}function isDirectory(fileName){if(fs.existsSync(fileName)) return fs.statSync(fileName).isDirectory();}function isFile(fileName){if(fs.existsSync(fileName)) return fs.statSync(fileName).isFile();}function readFile(fileName){if(fs.existsSync(fileName)) return fs.readFileSync(fileName,"utf-8");}

Two parameters: the first parameter is "folder name" and the second parameter is "the string you want to search"

Print the file path. When the task is finished, close the job. Speed is really tough, bright blind eyes... If you use java full-text search, you are miserable...

Nodejs search, read and write files

(1) path Processing

1. First, we need to pay attention to the file Path standardization. nodejs provides us with the Path module. The normolize method can help us standardize the Path:

var path = require('path');path.normalize('/foo/bar/nor/faz/..'); -> /foo/bar/nor

2. Of course, there are also join merge paths:

var path = require('path');path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); ->/foo/bar/baz/asdf

3. Resolution path

var path = require('path');path.resolve('/foo/bar', './baz'); ->/foo/bar/bazpath.resolve('/foo/bar', '/tmp/file/'); ->/tmp/file

4. Search for relative paths between two relative paths

var path = require('path');path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); ->../../impl/bbb

5. Extraction path

var path = require('path');path.dirname('/foo/bar/baz/asdf/quux.txt'); ->/foo/bar/baz/asdf=================var path = require('path');path.basename('/foo/bar/baz/asdf/quux.html') ->quux.html

You can even remove the extension name. You only need to input the second parameter in basename. The parameter is the extension name, for example:

Var path = require ('path ');

Path. basename ('/foo/bar/baz/asdf/quux.html', '.html ');-> quux

Of course, different files may exist in the file path, and we cannot hard-code the suffix to get the desired result,

So there is a way to get our Suffix:

Path. extname ('/a/B/index.html'); // => '.html'

Path. extname ('/a/B. c/Index'); // =>''

Path. extname ('/a/B. c/.'); // =>''

Path. extname ('/a/B. c/d.'); // => '.'

(2) File Processing

Var fs = require ('fs ');

1. Determine whether the file exists

Fs. exists (path, function (exists ){});

The above interface is asynchronous, so there is a callback function that can process our various operations in the callback. If you need synchronous operations, you can use the following method:

Fs. existsSync (path );

2. Read File status information

fs.stat(path, function(err, stats) {  if (err) { throw err;}  console.log(stats);});

The output content of states in the console is roughly as follows:

 { dev: 234881026, ino: 95028917, mode: 33188, nlink: 1, uid: 0, gid: 0, rdev: 0, size: 5086, blksize: 4096,blocks: 0,atime: Fri, 18 Nov 2011 22:44:47 GMT,mtime: Thu, 08 Sep 2011 23:50:04 GMT,ctime: Thu, 08 Sep 2011 23:50:04 GMT }


At the same time, stats also has some methods, such:

Stats. isFile (); stats. isDirectory (); stats. isBlockDevice (); stats. isCharacterDevice (); stats. isSymbolicLink (); stats. isFifo (); stats. isSocket ();. read/write file fs. open ('/path/to/file', 'R', function (err, fd) {// todo });

The second parameter is the operation type:

R: Read-Only

R +: read/write

W: file Rewriting

W +: overwrite the file. If the file does not exist, create

A: read and write files, append at the end of the file

A +: read and write files. If the file does not exist, create

The following is a small example of reading files:

 var fs = require('fs'); fs.open('./nodeRead.html', 'r', function opened(err, fd) { if (err) { throw err }   var readBuffer = new Buffer(1024),   bufferOffset = 0,   bufferLength = readBuffer.length,   filePosition = 100;   fs.read(fd,     readBuffer,    bufferOffset,    bufferLength,    filePosition,    function read(err, readBytes) {    if (err) { throw err; }    console.log('just read ' + readBytes + ' bytes');    if (readBytes > 0) {      console.log(readBuffer.slice(0, readBytes));    }  });});


The following is a small example of writing a file:

 var fs = require('fs'); fs.open('./my_file.txt', 'a', function opened(err, fd) {   if (err) { throw err; }   var writeBuffer = new Buffer('hello, world!'),   bufferPosition = 0,   bufferLength = writeBuffer.length, filePosition = null;   fs.write( fd,     writeBuffer,     bufferPosition,    bufferLength,    filePosition,    function(err, written) {      if (err) { throw err; }      console.log('wrote ' + written + ' bytes');  });});

For file read/write operations, we should not forget to close the operation after these operations are completed, that is, close (). The following is an encapsulation method, this includes the subsequent close operations on files for ease of use:

 var fs = require('fs'); function openAndWriteToSystemLog(writeBuffer, callback) {   fs.open('./my_file', 'a', function(err, fd) {     if (err) { return callback(err); }     function notifyError(err) {       fs.close(fd, function() {         callback(err);       });     }    var bufferOffset = 0,    bufferLength = writeBuffer.length,    filePosition = null;    fs.write( fd, writeBuffer, bufferOffset, bufferLength, filePosition,function(err, written) {      if (err) { return notifyError(err); }      fs.close(fd, function() {        callback(err);      });    });  });}openAndWriteToSystemLog(new Buffer('writing this string'),function(err) {  if (err) {    console.log("error while opening and writing:", err.message);    return;  }  console.log('All done with no errors');});
Related Article

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.