What would make a script to get stdout returns differently on different locations?

29 Views Asked by At
import * as path from "https://deno.land/[email protected]/path/mod.ts";
async function getStdout() {
    const dirname = path.dirname(path.fromFileUrl(import.meta.url))
    const cmd = new Deno.Command("pwsh", { args: ['-c', 'ls', dirname] });
    const { _code, stdout, _stderr } = await cmd.output();
    const decodedStdout = new TextDecoder().decode(stdout)
    console.log(decodedStdout)
}
await getStdout()

This script is simply to get the path of it, run pwsh -c ls $dirname and print the result back. If running on folder A it works fine, but on folder B it returns nothing. Surely there are files on B; running ls on B is fine.

However, if I change the command from ls to echo, then it works again.

What makes this happens?

1

There are 1 best solutions below

0
Ooker On

After a sleep I realize I didn't log the code and the stderr. This helps me debug:

if (code !== 0) {
    console.log(new TextDecoder().decode(stderr))
}

In my case, it's because I use spaces in filenames. The fix is to use template literals.

Full script:

import * as path from "https://deno.land/[email protected]/path/mod.ts";
async function getStdout() {
    const dirname = path.dirname(path.fromFileUrl(import.meta.url))
    console.log(dirname)
    const cmd = new Deno.Command("pwsh", { args: ['-c', 'ls', `'${dirname}'`] });
    const { code, stdout, stderr } = await cmd.output();
    const decodedStdout = new TextDecoder().decode(stdout)
    console.log(decodedStdout)

    if (code !== 0) {
        console.log(new TextDecoder().decode(stderr))
    }
}
await getStdout()

Take a look at Should I avoid using spaces in my filenames?