Home >Operation and Maintenance >Linux Operation and Maintenance >How to use Node.js to write a command line tool in Linux

How to use Node.js to write a command line tool in Linux

PHPz
PHPzforward
2023-05-14 14:08:021580browse

1. Goal

  1. Enter the command you wrote on the command line to complete the target task

  2. The command line requirement is globally valid

  3. The command line requirement can be deleted

  4. The command line function generates a file to display the current date

2. Code part

  1. Create a new file and name it sherryFile

  2. Contents of the file sherryFile

Introduction: Generate a file with the current date and creator

#! /usr/bin/env node
console.log('command start');
const fs = require('fs');
let date = new Date().toLocaleDateString();
let data = date + '\n\t' + '——create By karuru';
fs.writeFile('./date.txt', data, 'utf8', (err) => {
  if (err) {
    console.log('sherryFile command wrong', err);
    return false;
  }
  console.log('writeFile success!!!!');
  console.log('command end');
});
  1. Give the file execution permission chmod 755 sherryFile

  2. Enter ./sherryFile

  3. in the file path where the file is located. If the following content is output, the command execution is successful

command start
writeFile success!!!!
command end

In the file directory, there will be a new The date.txt file is generated with the following content

2/28/2018
create By karuru

Modify the command to be globally valid

ln sherryFile /usr/local/bin/sherryFile

Delete command

rm /usr/local/bin/sherryFile

The above is the detailed content of How to use Node.js to write a command line tool in Linux. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete