Simple analysis of Node.js search string function _node.js

Source: Internet
Author: User
Tags readfile

Requirements are as follows:

The entire directory under about 40 m, file countless, due to the time long, can not remember that string specific in which file, so. Powerful, bright blind eyes of the node.js shining debut:

Windows installation Node.js and installation of ordinary software is no different, after loading to open the Node.js shortcut, or direct cmd, you understand.

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 argument is "folder name" and the second argument is "the string you are looking for"

As shown in figure:

Print out file path, finish, call it off. The speed is really fierce, bright blind eyes ... If you use the Java Full-text Search, you are miserable ...

Nodejs lookup, read and write files

(1), Path handling

1. First of all, we need to pay attention to the normalization of the file path, Nodejs gives us the path module, Normolize method can help us normalize the path:

var path = require (' path ');

Path.normalize ('/foo/bar/nor/faz/. '); ->/foo/bar/nor

2. There are, of course, join merging 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/baz

path.resolve ('/foo/bar ', '/tmp/file/');->/tmp/file

4. Find a relative path between two relative paths

var path = require (' path ');

Path.relative ('/data/orandea/test/aaa ', '/data/orandea/impl/bbb '); .. /.. /impl/bbb

5. Draw away the 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 suffix name by passing in the second argument in BaseName, which is the suffix name, for example:

var path = require (' path ');

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

Of course there may be different files in the file path, and we can't hard-code the suffix to get the results we want,

So there's a way to help us get the suffix name:

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 a file exists

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

The above interface is asynchronous, so there is a callback function that can handle all of our operations in the callback, and if you need to sync, 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 contents of the console output states are 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, Nov 22:44:47 GMT,
mtime:thu, SEP 2011 23:50:04 GMT,
Ctime:thu, Sep 23:50:04 GMT}


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

Stats.isfile ();
Stats.isdirectory ();
Stats.isblockdevice ();
Stats.ischaracterdevice ();
Stats.issymboliclink ();
Stats.isfifo ();
Stats.issocket ();
. Read and Write Files

fs.open ('/path/to/file ', ' R ', function (err, FD) {

//Todo

});

The second parameter is the action type:

R: Read Only

R+: Reading and writing

W: Rewriting files

w+: Rewrite file, create if file does not exist

A: Read and write files, append at end of file

A +: Read and write files, if the file does not exist, create

The following is a small example of a read file:

 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 = m;
   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));
    }
  });


Here 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 and write operations, we should not forget to perform the shutdown operation after all these operations, that is, close (); The following is an encapsulated method that includes a late shutdown of the file, which is easy to 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 Notif Yerror (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 do with no errors ');

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.