【问题标题】:how could i use require() to read a local json file by just adding the local project json file path?我如何使用 require() 通过添加本地项目 json 文件路径来读取本地 json 文件?
【发布时间】:2020-12-24 00:12:23
【问题描述】:

这就是我设法读取 json 文件的方法

posts.js 文件

const PATH = require('/Users/jorgesisco/Dropbox/Programming_Practice/Web_Development/PWJ/Module-8/Blog/pwj-module-8-my-blog-api/exercise/data.json');

class Post {
  get() {
    // get posts
  }
  getIndividualBlog() {
    // get one blog post
  }

  addNewPost() {
    // add new post
  }

  readData() {
    return PATH; 
  }
}
module.exports = Post;

现在在 app.js 中我调用该函数,我可以在 postman 中看到 json 文件。

// 1st import express
const express = require('express');
const app = express();
const Post = require('./api/models/posts');
const postsData = new Post();

const posts = [
  {
    id: '1581461442206',
    title: 'This is a New Blog Post',
    content: 'This is the content! ',
    post_image: 'uploads/post-image-1581461442199.jpg',
    added_date: '1581461442206',
  },
];
// const result = posts.flatMap(Object.values);

app.get('/api/posts', (req, res) => {
  res.status(200).send(postsData.readData());//here I call the function to see json file in postman
});

app.listen(3000, () => console.log('listening on http://localhost:3000'));

我认为我不应该使用 json 文件的整个文件路径,但是当我只使用 ./data.json 之类的东西时,会发生错误,因为它找不到 json 文件。

【问题讨论】:

    标签: javascript node.js json require


    【解决方案1】:

    要从同一目录访问文件,您需要传递 './' 示例:require('./data.json');

    用于从当前目录'../' 中的一个目录访问文件 示例:require('../data.json');

    用于访问来自不同文件夹 '../../foldername/data.json' 中的两个目录的文件 示例:require('../../dataFolder/data.json');

    【讨论】:

      【解决方案2】:

      文件路径是从您运行主代码 (app.js) 的目录中引用的

      1. 将 data.json 文件移动到代码所在的目录中。假设main_code/datadir。所以,它现在看起来像这样 -
      -- maincode
         -- datadir
            -- data.json
         -- posts.js
         -- app.js
      
      1. 将posts.js 代码中的文件引用为require('./datadir/data.json')(假设datadir/ 与您的app.js 代码位于同一路径/级别)
      2. 运行 app.js

      【讨论】:

      • 谢谢老兄!它有效,但这可以吗?检查一下:prnt.sc/ubos3z json 数据应该在主项目文件夹中吗?
      • 它可以在文件系统上的任何地方,但是将它保存在项目文件夹中可以很容易维护。如果有帮助,请采纳答案,干杯!
      猜你喜欢
      • 2021-05-31
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 2019-05-29
      相关资源
      最近更新 更多