javascript - 在 Windows 脚本宿主中获取 javascript 文件路径

标签 javascript windows directory path windows-scripting

当使用通过 Windows Script Host 运行的 .js 文件时,是否可以获取正在运行的 .js 文件的路径(与当前工作目录不同)?换句话说,我想要类似于 PowerShell 的 $PSScriptRoot 变量的东西。有什么办法可以得到这个吗?

我想要这个的原因是因为执行这些脚本时的工作目录并不总是与 .js 文件本身的位置相同,但我希望我的代码引用相对于 .js 文件位置的内容.

最佳答案

You can get this with Node Js 

    const path = require('path'); // you can install this with npm

    // __dirname = C:\dev\project
    // __filename = C:\dev\project\index.js
    const dir= path.basename(__dirname);
    const archive= path.basename(__filename);
    const fullpath = path.join(dir, archive);

    console.log('Dir:', dir); // Dir: test
    console.log('Archive:', archive); // Archive: index.js
    console.log('Dir + Archive:', fullpath); // Dir + Archive: project\index.js

关于javascript - 在 Windows 脚本宿主中获取 javascript 文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59776887/

相关文章:

javascript - Google Drive & vuejs3 - 将文件上传到特定文件夹

Windows 批处理 - 将多个文本文件连接成一个

php - while(false !== ($f=readdir($d))){ 的解释

csv - 使用子目录时如何修复文件访问?

javascript - 将 HTML 写入新窗口打开的问题

javascript - 根据 PHP 变量值更改类

C++ - EncryptMessage 没有加密正确的数据

c++ - HRESULT:区分自定义代码和系统一

shell - 如何从查找 "type d"中排除此/当前/点文件夹

javascript - 如何在 Angular js 中返回 html 代码作为过滤器的输出