NodeJS使用相对路径访问文件 [英] NodeJS accessing file with relative path

查看:716
本文介绍了NodeJS使用相对路径访问文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个直接的问题。但是我无法解决这个问题。
在helper1.js中,我想访问foobar.json(从 config / dev /

  root 
-config
--dev
--- foobar.json
-helpers
--helper1.js

我无法让此工作 fs:如何查找父文件夹?



任何

解决方案

您可以使用路径加入目录的路径,其中 helper1.js 的目录位于 foobar.json 的相对路径。这将给你绝对路径 foobar.json

  var fs = require('fs'); 
var path = require('path');

var jsonPath = path.join(__ dirname,'..','config','dev','foobar.json');
var jsonString = fs.readFileSync(jsonPath,'utf8');

这应该在Linux,OSX和Windows上工作,假设UTF8编码。


It seemed like a straight forward problem. But I amn't able to crack this. Within helper1.js I would like to access foobar.json (from config/dev/)

root
  -config
   --dev
    ---foobar.json
  -helpers
   --helper1.js

I couldn't get this to work fs: how do I locate a parent folder?

Any help here would be great.

解决方案

You can use the path module to join the path of the directory in which helper1.js lives to the relative path of foobar.json. This will give you the absolute path to foobar.json.

var fs = require('fs');
var path = require('path');

var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');

This should work on Linux, OSX, and Windows assuming a UTF8 encoding.

这篇关于NodeJS使用相对路径访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆