Member-only story
Recursive Function and Variable Scope in Javascript
A Pythonian’s adventure on the “Recursive Function Mountain” in NodeJS.
Although both Python and Javascript are popular interpret languages, they tend to dominate different domains with little overlap. As a data professional I am proficient in Python but have remained at a beginner level with Javascript for years.
Stepping out of the comfort zone, however, often brings unexpected benefits. This has exactly happened to me when I had to refactor a legacy NodeJS codebase. In particular, I needed to write a function that recursively list the paths of all files in a folder. Suppose a simple folder is structured like this:
Then the result should be like this:
[‘test/folder1/file2’, ‘test/file1’]
With a recursive function, this isn’t hard in Python:
import os
def recursiveGetFiles(directory: str) -> list:
res = []
files = os.listdir(directory)
for file in files:
fullPath = os.path.join(directory, file)
if not os.path.isdir(fullPath):
res.append(fullPath)
else:
res += recursiveGetFiles(fullPath)
return res
if __name__ == '__main__':
print(recursiveGetFiles('test'))





