How to use the ls function from shelljs

Find comprehensive JavaScript shelljs.ls code examples handpicked from public code repositorys.

shelljs.ls is a method provided by the ShellJS library that allows you to list the contents of a directory in Node.js.

0
1
2
3
4
5
6
7
8
9
const fs = require('fs');
const sh = require('shelljs');

const { fileExists, dirExists } = require('./utils');

const srcContents = sh.ls('src');

// We don't want to commit built files, so it is useful to have a `clean` script which deletes them if they exist.
// However, Reactochart is built in the root directory
// (so that modules may be required with eg. `require('reactochart/LineChart')`).
fork icon56
star icon535
watch icon20

128
129
130
131
132
133
134
135
136
137
}

console.log(`[${widgetName}] Tested!`);

async function prepareWidget() {
    const filesToRemove = ls(workDir)
        .filter(file => file !== "node_modules")
        .map(file => join(workDir, file));
    if (filesToRemove.length) {
        rm("-r", ...filesToRemove);
fork icon8
star icon5
watch icon8

+ 4 other calls in file

How does shelljs.ls work?

shelljs.ls is a method of the ShellJS library that allows you to list the contents of a directory. When called with a directory path as an argument, it returns an array of filenames contained in that directory. If no argument is provided, it returns an array of filenames in the current working directory. It also provides various options to customize the output.

125
126
127
128
129
130
131
132
133
134
// Try to auto-detect java in the default install paths.
var oldSilent = shelljs.config.silent;
shelljs.config.silent = true;
var firstJdkDir =
    shelljs.ls(process.env['ProgramFiles'] + '\\java\\jdk*')[0] ||
    shelljs.ls('C:\\Program Files\\java\\jdk*')[0] ||
    shelljs.ls('C:\\Program Files (x86)\\java\\jdk*')[0];
shelljs.config.silent = oldSilent;
if (firstJdkDir) {
    // shelljs always uses / in paths.
fork icon2
star icon0
watch icon0

+ 5 other calls in file

192
193
194
195
196
197
198
199
200
201
    .setMaxSdkVersion(platformConfig.getPreference('android-maxSdkVersion', 'android'))
    .setTargetSdkVersion(platformConfig.getPreference('android-targetSdkVersion', 'android'))
    .write();

var javaPattern = path.join(locations.root, 'src', orig_pkg.replace(/\./g, '/'), '*.java');
var java_files = shell.ls(javaPattern).filter(function(f) {
    return shell.grep(/extends\s+CordovaActivity/g, f);
});

if (java_files.length === 0) {
fork icon2
star icon0
watch icon0

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
const shell = require("shelljs");

// List all files in the current directory.
const files = shell.ls();

console.log(files);

This code will print the names of all files in the current directory to the console.

125
126
127
128
129
130
131
132
133
134
135
 */
function files(options, source) {
    if (source) {
        return Shell.ls(options, source);
    }
    return Shell.ls(options);
}


/**
 * Create the directory if it doesnt exists
fork icon0
star icon3
watch icon0

+ 3 other calls in file

305
306
307
308
309
310
311
312
313
314
315
    }
}


// remove the default resource name from all drawable folders
function deleteDefaultResourceAt(baseDir, resourceName) {
    shell.ls(path.join(baseDir, 'res/drawable-*'))
    .forEach(function (drawableFolder) {
        var imagePath = path.join(drawableFolder, resourceName);
        shell.rm('-f', [imagePath, imagePath.replace(/\.png$/, '.9.png')]);
        events.emit('verbose', 'Deleted ' + imagePath);
fork icon1
star icon2
watch icon1

+ 33 other calls in file

52
53
54
55
56
57
58
59
60
61
function copyJsAndLibrary(projectPath, shared, projectName) {
    var nestedCordovaLibPath = getFrameworkDir(projectPath, false);
    shell.cp('-f', path.join(ROOT, 'framework', 'assets', 'www', 'cordova.js'), path.join(projectPath, 'assets', 'www', 'cordova.js'));
    // Don't fail if there are no old jars.
    setShellFatal(false, function() {
        shell.ls(path.join(projectPath, 'libs', 'cordova-*.jar')).forEach(function(oldJar) {
            console.log("Deleting " + oldJar);
            shell.rm('-f', oldJar);
        });
        // Delete old library project if it existed.
fork icon0
star icon2
watch icon1

+ 9 other calls in file

122
123
124
125
126
127
128
129
130
131
    
// get the path for the directory of the current file
let folderDirectory = path.dirname(file);

// loop each file in the folder and copy it if it has not been created yet
shell.ls(path.dirname(file)).forEach((copyFile) => {
    let originalFilePath = folderDirectory + '/' + copyFile;
    let copyFilePath = DEPLOY_FOLDER + '/' + originalFilePath;

    if (!shell.test('-f', copyFilePath)) {
fork icon0
star icon0
watch icon1

+ 42 other calls in file

22
23
24
25
26
27
28
29
30
31
32
33
  's': 1,
};


// Contains the list of tests which should be built and profiled
const profileTests =
    shell.ls(baseDir).filter((filename) => fs.statSync(path.join(baseDir, filename)).isDirectory());


// build tests
shell.exec(
    `yarn bazel build ` +
fork icon0
star icon0
watch icon1

+ 9 other calls in file

89
90
91
92
93
94
95
96
97
98
.then(() => {
  // Create destination path
  const destinationDirectory = `${destDirectory}/${folderName}`;

  // Remove old files
  shell.ls(destinationDirectory).forEach(file => {
    const extension = fileExtension(file);
    if (this.includes(extension)) {
      const fullPath = `${destinationDirectory}/${file}`;
      shell.rm(fullPath);
fork icon0
star icon0
watch icon1

+ 12 other calls in file

2
3
4
5
6
7
8
9
10
11
12
13
const logDir = '~/AppData/Roaming/slobs-client/node-obs/logs';
let tail;
let currentLog;


setInterval(() => {
  const logs = sh.ls(logDir);
  const lastLog = logs[logs.length - 1];


  if (lastLog !== currentLog) {
    if (tail) {
fork icon0
star icon0
watch icon0

101
102
103
104
105
106
107
108
109
const web3 = new Web3(truffleProvider);

const chainId = await web3.eth.getChainId();
const networkId = await web3.eth.net.getId();

const [ozFile] = shell.ls(`.openzeppelin/*-${chainId}.json`);
const { admin: { address: adminAddress } } = JSON.parse(shell.cat(ozFile));

const admin = new web3.eth.Contract(proxyAdminAbi, adminAddress);
fork icon0
star icon0
watch icon0

12
13
14
15
16
17
18
19
20
21
22
// sh.rm('-rf','out/Release');//强制递归删除`out/Release目录`
// sh.cp('-R','stuff/','out/Release');//将`stuff/`中所有内容拷贝至`out/Release`目录


// sh.cd('lib');//进入`lib`目录
// //找出所有的扩展名为js的文件,并遍历进行操作
// sh.ls('*.js').forEach(function (file) {
//   /* 这是第一个难点:sed流编辑器,建议专题学习,-i表示直接作用源文件 */
//   //将build_version字段替换为'v0.1.2'
//   sh.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
//   //将包含`REMOVE_THIS_LINE`字符串的行删除
fork icon0
star icon0
watch icon0