Search code examples
javascriptarrayscommanddos

How can i use dos batch file to get a list of folders in a folder and convert it into a javascript array?


How can I use a dos batch file to get a list of folders in a main folder and convert it into a JavaScript array?

I know:

set foldersList = dir /b /ad ""
%foldersList% > file.txt

Will give me a list of the folders with newline between them, but I don't know how to convert it to something like this:

var foldersList = ['name1','name2,..... ]

Solution

  • How about if your batch file outputted it to a formatted JS include as plain text into the HTTP Dir, and your HTML included it. For example

    del "c:\httpdocs\mywebsite\protectedincludes\vars.js"
    set foldersList = dir /b /ad ""
    %foldersList% > tempfile.txt
    echo "var myJsArray=[" > "c:\httpdocs\mywebsite\protectedincludes\vars.js" 2>&1
    FOR /f %a in (‘tempfile.txt’) do (
    echo "'" > "c:\httpdocs\mywebsite\protectedincludes\vars.js" 2>&1
    echo %a > "c:\httpdocs\mywebsite\protectedincludes\vars.js" 2>&1
    echo "'," > "c:\httpdocs\mywebsite\protectedincludes\vars.js" 2>&1
    )
    echo "];" > "c:\httpdocs\mywebsite\protectedincludes\vars.js" 2>&1
    

    and then on your webpage you can easily include it:

    <html>
    <script src="protectedIncludes/vars.js"></script>
    <script> Do something with myJsArray </script>
    

    Something along these lines anyway. Bedtime for me now though. edit. couple of typos.