博客
关于我
node全局变量 __dirname __filename 获取绝对路径
阅读量:264 次
发布时间:2019-03-01

本文共 415 字,大约阅读时间需要 1 分钟。

__dirname 和 __filename 获取绝对路径

在 Node.js 中,获取文件或文件夹的绝对路径可以通过两个全局变量轻松实现:__dirname 和 __filename。

这些变量的含义如下:

  • __dirname:表示当前文件所在目录的绝对路径。
  • __filename:表示当前文件的绝对路径。

这些全局变量具有以下特点:

  • 变量特性:在不同文件中值不同,随文件位置变化而变化。
  • 全局特性:可以在任何位置直接使用,无需声明。

测试使用方法很简单,随时随地都可以执行:

console.log(__dirname); console.log(__filename);

在文件操作中,建议使用绝对路径,可以通过以下方式构建:

const fs = require('fs');const filePath = __dirname + '\\html5.jpg';

即使是在复杂文件系统中,这种方法依然能有效获取文件路径。

转载地址:http://bdca.baihongyu.com/

你可能感兴趣的文章
Python: AES加密与解密
查看>>
Python: Range() 最大尺寸;动态的还是静态的?
查看>>
Python: Windows下用 multiprocessing 的深坑
查看>>
python:Could not find platform independent libraries <prefix>解决方法
查看>>
Python:datetime tzinfo 时区名称文档
查看>>
Python:deepcopy(list) vs new_list = old_list[:]
查看>>
Python:Google API - 从消息中获取 mimeTypes
查看>>
Python:Google API - 从消息中获取 mimeTypes
查看>>
Python:subprocess.call,stdout to file,stderr to file,在屏幕上实时显示stderr
查看>>
Python:TypeError:无法连接“str“和“int“对象
查看>>
Python:XPath 在 ElementTree 中不可用
查看>>
Python:从 FTP 服务器下载文件
查看>>
python:从列表中创建元组列表
查看>>
Python:从嵌套列表中删除重复项
查看>>
Python:从间隔映射到值
查看>>
Python:使用 shell=False 的子进程调用不起作用
查看>>
Python:修改 PATH 环境变量的平台无关方式
查看>>
Python:假与 0
查看>>
Python:函数使用
查看>>
Python:函数进阶
查看>>