问题描述
这就是我设法读取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中,我调用了该函数,并且能够在邮递员中看到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文件,会发生错误。
解决方法
要从同一目录访问文件,您需要传递'./'
示例:require('./data.json');
用于从当前目录'../'
的一个目录访问文件
示例:require('../data.json');
用于从不同文件夹'../../foldername/data.json'
中的两个目录访问文件
示例:require('../../dataFolder/data.json');
文件路径是从运行主代码(app.js)的目录中引用的。
- 将data.json文件移动到代码所在的目录中。假设
main_code/datadir
。所以,现在看起来像这样-
-- maincode
-- datadir
-- data.json
-- posts.js
-- app.js
- 用
require('./datadir/data.json')
(参考datadir/
与app.js
代码相同的路径/级别)来引用posts.js代码中的文件 - 运行app.js