felix-cao / Blog

A little progress a day makes you a big success!
31 stars 4 forks source link

Nodejs 路径问题 #165

Open felix-cao opened 5 years ago

felix-cao commented 5 years ago

__dirname

当前模块的目录名,这与 __filenamepath.dirname() 相同。

即当前执行文件所在目录的绝对路径

Running node example.js from /Users/mjr

console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr

__filename

当前的文件名。当前执行文件的带有完整绝对路径的文件名

Running node example.js from /Users/mjr

console.log(__filename);
// Prints: /Users/mjr/example.js
console.log(__dirname);
// Prints: /Users/mjr

module.paths

Nodejs 每个模块都有一个本地的对象 module

module.paths, 当前模块(运行的文件)所在的绝对路径

process.cwd(),

process.cwd() 方法返回 Node.js 进程的当前工作目录。 cwd 是 Current Working Directory 的简写。 process.cwd()方法返回的路径不是唯一的,会根据node命令的执行环节路径更改。

跨平台路径解决方案

windows下的路径写法为

__dirname +"\images\ol.jpg";

linux 下 就是

__dirname +"/images/ol.jpg"; 那么 怎么统一那

引用path 用join方法

var path= require("path");
path.join(__driname+"/images/lo.jpg");

读取文件或目录

同步的方式读取目录

https://www.cnblogs.com/samve/p/10805908.html