How to list items in directory in Nim

Viewed 468

I'm currently working on an application that should be able to list out the items in a directory, however, after looking at the OS module in Nim, I couldn't find a way to see what is inside a directory. Is it possible that it hasn't been implemented yet, or did I maybe just look at the wrong place to find such a function?

So in short, how can I see what is inside /home/username/Documents/? How can I list out its content in Nim?

2 Answers

You need to look in the Iterators section of the os module.

There is walkDir and related iterators for this purpose:

iterator walkDir(dir: string; relative = false; checkDir = false): tuple[
    kind: PathComponent, path: string]

Walks over the directory dir and yields for each directory or file in dir. The component type and full path for each item are returned.

You can use it like this:

import os

for kind, path in walkDir("/home/username/Documents/"):
  case kind:
  of pcFile:
    echo "File: ", path
  of pcDir:
    echo "Dir: ", path
  of pcLinkToFile:
    echo "Link to file: ", path
  of pcLinkToDir:
    echo "Link to dir: ", path

Recursive traversal of subfolders with filtering by extensions:

import os
import sequtils

let
    targetFolder = "/home/user/media/"
    targetExt = @[".mp3", ".webm", ".mkv"]

proc scanFolder (tgPath: string, extLst: seq[string]): seq[string] =
    var
        fileNames: seq[string]
        path, name, ext: string
        
    for kind, obj in walkDir tgPath:
    
        if $kind == "pcDir" :
            fileNames = concat(fileNames, scanFolder(obj, extLst))

        (path, name, ext) = splitFile(obj)

        if ext in extLst:
            fileNames.add(obj)

    return fileNames 
            

var fileList = scanFolder(targetFolder, targetExt)   

for f in fileList:
    echo f
Related