Absolute paths & require()
2015-07-03 11:51
387 查看
转载:https://coderwall.com/p/th6ssq/absolute-paths-require
A quick one:
Normally, when referencing a file with
path is used. This path must reflect the position of the current file within your site's directory structure.
However, I'd rather use an absolute path based only on my site's top-level directory, and not on whichever file I'm currently in.
So, I include this snippet at the top of my
Now when you're in a file, instead of writing something like this:
You can write this:
Not only is this more readable, you also don't have to remember where in the file hierarchy you are when you'd like to include something.
Another benefit is that you won't have to update any paths if you move a file containing an
Lastly, when you need to get the full path to a file (perhaps for use with the fs module) you can use the global function:
A quick one:
Normally, when referencing a file with
require()a relative
path is used. This path must reflect the position of the current file within your site's directory structure.
However, I'd rather use an absolute path based only on my site's top-level directory, and not on whichever file I'm currently in.
So, I include this snippet at the top of my
main.js:
global.base_dir = __dirname; global.abs_path = function(path) { return base_dir + path; } global.include = function(file) { return require(abs_path('/' + file)); }
Now when you're in a file, instead of writing something like this:
require('../../../lib/Utils.js');
You can write this:
include('lib/Utils.js');
Not only is this more readable, you also don't have to remember where in the file hierarchy you are when you'd like to include something.
Another benefit is that you won't have to update any paths if you move a file containing an
include().
Lastly, when you need to get the full path to a file (perhaps for use with the fs module) you can use the global function:
abs_path('lib/Utils.js');
相关文章推荐
- 获取运行中的TeamViewer的账号和密码(Test on English GUI)
- hibernate : No positional parameters in query 错误解决办法
- IOS开发学习笔记——UITabBarController
- [tarjan] hdu 3836 Equivalent Sets
- Android 建造者(Builder)模式
- 如何使用NSOperations和NSOperationQueues(二)
- 设计模式读书笔记:Builder(建造者)
- UEFI是什么?与BIOS的区别在哪里?UEFI详解!
- iOS UINavgationController、 UINavigationBar、 UINavigationItem关系分析
- 自已实现一个UI库-实现Windows的一个模拟器
- 自已实现一个UI库-实现画图API接口
- emulator: ERROR: x86 emulation currently requires hardware acceleration!Please ensure Intel HAXM is
- UITabbar 显示小红点 (消息提示)
- 设计师成长的五个阶段。
- 如何ScrollView在XIB或者Storyboard中设置约束并实现翻页滚动效果
- StringBuilder与StringBuffer联系与区别
- 自已实现一个UI库
- 完全代码实现UITableView下拉更新,异步请求数据
- UIScrollView的简单使用 以及一些常用属性
- UIautomator运行步骤