“This is the fifth day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

This article summarizes the process of writing scripts using NodeJS and some common scenarios.

In general, we use the shell to write scripts, but shell syntax is difficult to remember and not easy to use, so front-end programmers are recommended to use javascript to write scripts.

Note that the script is executed only if the node environment is installed on the computer.

The simplest script

Enter the following in the editor:

#! /usr/bin/env node
console.log('hello world');
Copy the code

Save it as test, execute the script node test, and get the output on the console.

Further, we give the script an execute permission,

chmod 755 test
Copy the code

You can then execute the script through./test

Example – read all files in a given folder

Reading the current folder uses the fs.readdirSync method, which returns an array of all subfolders or files in a given folder.

For example, I have a test folder in the current directory

Test ├── 1.html ├── 1.txt ├─ filesCopy the code

Fs. ReaddirSync (‘/test ‘) output for [‘ 1. HTML ‘, ‘1. TXT’ and ‘files’]

Create a new file, getFile, to store the script code

Write dead folder

Read all files in a given directory and output the following code:

#! /usr/bin/env node

const testFolder = './test/';
const fs = require('fs');

fs.readdirSync(testFolder).forEach(file= > {
  console.log(file);
});
Copy the code

Get user input

The given path of the above code is writable and we need to input it as an argument. Nodejs reads the user’s input method:

const [nodeEnv,dir,...args]=process.argv //args is a parameter entered by the user
Copy the code

Modify script code:

#! /usr/bin/env node

const fs = require('fs');
const [nodeEnv,dir,...args]=process.argv

// Obtain the path entered by the user
const folder=args[0]

fs.readdirSync(folder).forEach(file= > {
  console.log(file);
});
Copy the code

The path can now be entered by itself when the script is executed

Node getFile Your pathCopy the code

Recursive read

The above code can only read one layer, and cannot handle the case of subfolders under the folder, so to handle subfolders, change to recursive read

The recursive reading method is as follows:

function walkSync(currentDirPath, callback) {
    fs.readdirSync(currentDirPath).forEach(function (name) {
        var filePath = path.join(currentDirPath, name);
        var stat = fs.statSync(filePath);
        if (stat.isFile()) {
            callback(filePath, stat);
        } else if(stat.isDirectory()) { walkSync(filePath, callback); }}); }Copy the code

ReaddirSync reads a given directory, gets an array, iterates through the array, and if there are folders in the array, reads recursively. The above method receives a callback for each file

The modified getFile code is as follows:

#! /usr/bin/env node

const fs = require('fs');
const path=require('path')


function walkSync(currentDirPath, callback) {
    fs.readdirSync(currentDirPath).forEach(function (name) {
        var filePath = path.join(currentDirPath, name);
        var stat = fs.statSync(filePath);
        if (stat.isFile()) {
            callback(filePath, stat);
        } else if(stat.isDirectory()) { walkSync(filePath, callback); }}); }; (function(){
    const [nodeEnv,dir,...args]=process.argv
    // Obtain the path entered by the user
    const folder=args[0]
    walkSync(folder,(filePath,stat) = >{
        FilePath is the filePath and stat is the file information
    })
}())

Copy the code

With a list of files, we can do many things, such as:

  • Rename and move files in batches
  • Batch image compression
  • Video and audio batch conversion encoding format

However, the above functions need to be implemented with the help of other third-party libraries, which will be explained in the next article.