diff --git a/test.mjs b/test.mjs index c2ddf69fce..ac69ba5511 100755 --- a/test.mjs +++ b/test.mjs @@ -80,8 +80,9 @@ import {strict as assert} from 'assert' } } -{ // Scripts with no extension are working +{ // Scripts with no extension work and do not overwrite similarly named files. await $`node zx.mjs tests/no-extension` + assert.match((await fs.readFile('tests/no-extension.mjs')).toString(), /Test file to verify no-extension didn't overwrite similarly name .mjs file./); } { // require() is working from stdin diff --git a/tests/no-extension.mjs b/tests/no-extension.mjs new file mode 100755 index 0000000000..da10c2b26f --- /dev/null +++ b/tests/no-extension.mjs @@ -0,0 +1 @@ +// Test file to verify no-extension didn't overwrite similarly name .mjs file. diff --git a/zx.mjs b/zx.mjs index f4cb6d4d5a..a47d30e7dd 100755 --- a/zx.mjs +++ b/zx.mjs @@ -101,10 +101,15 @@ async function writeAndImport(script, filepath, origin = filepath) { async function importPath(filepath, origin = filepath) { let ext = extname(filepath) + if (ext === '') { + let tmpFilename = fs.existsSync(`${filepath}.mjs`) ? + `${basename(filepath)}-${Math.random().toString(36).substr(2)}.mjs` : + `${basename(filepath)}.mjs` + return await writeAndImport( await fs.readFile(filepath), - join(dirname(filepath), basename(filepath) + '.mjs'), + join(dirname(filepath), tmpFilename), origin, ) }