Nodejs Write (add timestamp) command-line tool timestamp

Source: Internet
Author: User
Tags add time readfile

Nodejs In addition to writing server-side programs can also write command-line tools, such as Gulp.js is Nodejs written.

Next, let's implement a command to add a timestamp: $ timestamp Action

https://www.npmjs.com/package/timestamp007

1. Modules to be used:

Commander Module

    • Purpose: Parse command line arguments
    • Home: https://tj.github.io/commander.js/

FS Module

    • Purpose: To read and write the system files and directories

2. Command format

Before you write a command-line tool, you first define how the command is used:

Such as:

    • The project file directory under $ timestamp action indicates that all pages under the project will be added a timestamp
    • 给某个页面添加时间戳 $ timestamp action /project/index.html  
    • 在非项目录下运行 需要制定项目目录 $ timestamp action /Users/river/web

3. Common command formats

command [options] [arguments]

The meaning is as follows:

    • Command: Name, such as: Node,timestamp
    • options:--words or single letters, such as--HELP or--h
    • Arguments: Parameters

When you view the command Help, [],<>,| and other symbols, their meanings are

    • []: Optional
    • <>: Represents a mutable option. It is usually more than one choice. And it's one of the required choices.
    • X| y| Z Multiple Select one, if added [], it is not optional.
    • -ABC: Multiple selection, if added [], it is optional.

The use of the timestamp command is described as follows:

Usage:timestamp [Options] [command]

-------------------------------------------------------------

Next, we step through the creation of our command line project:

1. First create an empty project folder and then initialize the Package.json folder with NPM init:

$ mkdir Timestamp

$ cd Timestamp

$ NPM Init

2. After initialization is complete

To install the Commander module:

$ NPM Install Commander--save;

To install the FS module:

$ NPM Install FS--save

3. After the installation is complete

New file Bin/timestamp;

The file code is as follows:

#!/usr/bin/env nodevarProgarm = require (' Commander '));//Command Version numberProgarm.version (' 0.0.1 ');//Help commandprogarm. Command (' Help '). Description (' Show use Help '). Action (function() {progarm.outputhelp (); });p rogarm. Command (' Action [dir] '). Description (' Add time stamp '). Action (Require (‘.. /lib/readfile '). Action (function(dir) {Console.log ("Geek")    }); //Start parse CommandProgarm.parse (PROCESS.ARGV)

The first line of the file:

#!/usr/bin/env node   : Specifies which interpreter is used by the current file to execute.

Progarm    . Command (' Help ')    . Description (' Show usage assistance ')    . Action (function() {        Progarm.outputhelp ();    });  
    • Command ("Help") indicates what commands are currently
    • . Description (' Show usage help ') current command
    • . Action (callback); The callback function that resolves to the current command execution
    • Progarm.parse (PROCESS.ARGV) starts parsing commands

4. Writing Readfile.js

Under the timestamp directory

$ mkdir Lib

cd Lib

Create a new readfile.js with the following file contents:

varFS = require (' FS ');//calling the FS moduleModule.exports =function(dir) {//The directory that is passed in, and if there are no parameters, defaults to the current directorydir = Dir | | ‘.‘; if(Dir.indexof (". html") > 0) {addtimestimp (dir);//If the parameter is an. html file}Else{fs.readdir (dir,function(Err, files) {//if it is not an HTML file, traverse all the. html files under the folder            if(Err) {Console.log (err)}Else{Files.foreach (function(index) {varPath = dir + "/" +index; if(Index.indexof ('. html ') > 0) {addtimestimp (path); }                })            }        })    }};functionAddtimestimp (path) {fs.readfile (path,' Utf-8 ',function(Err, data) {//Read File contents        if(Err) {Console.log (err)}Else {            varNowtime =Date (); vartimestamp = Date.parse (nowtime);//Create a timestamp at the current time            varNewcss = ". css?t=" +timestamp; varTestcss =/[.] {1}css (\?t=[0-9]{0,})?G; varNewjs = ". js?t=" +timestamp; varTestjs =/[.] {1}js (\?t=[0-9]{0,})?F; varNewpng = ". png?t=" +timestamp; varTestpng =/[.] {1}png (\?t=[0-9]{0,})?G; varNewjpg = ". jpg?t=" +timestamp; varTestjpg =/[.] {1}jpg (\?t=[0-9]{0,})?G; varNewData =(((Data.replace (Testcss, NEWCSS)). Replace (Testjs, NEWJS)). Replace (Testpng, newpng)) . Replace (testjpg, newjpg); Fs.writefile (Path, NewData,function(ERR) {//add timestamp after write                if(Err) {Console.log (err); } Else{console.log (path+ "Add timestamp complete")                }            }); }    })}

5. Edit Package.json

{  "Name": "Timestamp007",  "Version": "0.0.6",  "description": "Add a timestamp to the HTML files",  "Main": "Index.js",  "Scripts": {    "Test": "Echo \" Error:no test specified\ "&& exit 1"  },  "Author": "River.cao",  "License": "ISC",  "Bin": {    "Timestamp": "./bin/timestamp"  },  "Repository": {  ' type ': ' Git ',  "url": "Https://github.com/caojiangtao/timestamp"  },  "Dependencies": {    "Commander": "^2.9.0",    "FS": "0.0.2"  }}

You can see that Package.json adds the Bin property, so what does the Bin property do?

The Bin property is used to specify the command to which the current module needs to connect, where we specify the timestamp command to execute the file:

./bin/timestamp

Here's the point. In order for this setting to take effect, you also need to execute the following command to connect

$ sudo npm link

Then I can verify that the command line is in effect and that the execution is complete.

Next Execute:

$ timestamp Help

If you see something like this:

  Usage:timestamp [options] [command]  Commands:          help display using helper    action [dir]  timestamp  Options:    -H,--help     output usage    information-V,--version  output the version number

Indicates that our command line has been written successfully!

It's done! Can open a bottle of sprite 82 years to celebrate!!!

Wait, I think it's still going to be released to NPM to share the fruits of labor with the brothers,

So how do you publish it to NPM?

First of all, you have a NPM account.

1, Register NPM account

$ npm Adduserusername:river.caopassword:email:[email protected]

2. Go back to the timestamp root directory to perform NPM publish, if there are no error prompts then release the results, go to http://search.npmjs.org/to see it, your module should already appear in the "Latest Updates" column. (Of course the Ken will be wrong, because the module name is already occupied)

So Nodejs's command-line development is over, you can go and drink sprite.

Nodejs Write (add timestamp) command-line tool timestamp

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.