简体   繁体   English

Node.js fs 在 console.log 上显示未定义

[英]Node js fs is showing undefined on console.log

I was working on a Next.js blog, I have completed the frontend and I was making backend using the next.js我正在写一个 Next.js 博客,我已经完成了前端,我正在使用 next.js 制作后端

./pages/api

I made a file我做了一个文件

./pages/api/blogs.js

I made some json files in ./data folder as dummy data我在./data文件夹中制作了一些 json 文件作为虚拟数据

./data/hello.json
{
"title" : "This is hello",
"description" : "This is description",
"content" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto quasi error cumque iure tempore officiis quaerat rerum delectus hic reprehenderit. Iure, eveniet repudiandae. Consequuntur obcaecati eius sequi similique officia beatae quibusdam blanditiis."
}

I write this code in ./pages/api/blogs.js我把这段代码写在./pages/api/blogs.js

import * as fs from 'fs'

export default function handler(req, res) {
    fs.readFile("../../data/hello.json", (err,data)=>{
        console.log(data)
    })
    res.status(200).json({"name" : "Shivam Bhai"})
}

but my server console is showing undefined.但我的服务器控制台显示未定义。 I also tried loging err on console and this was result我也尝试在控制台上记录错误,这是结果

    [Error: ENOENT: no such file or directory, open 'C:\projects\data\hello.json'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'open',
  path: 'C:\\projects\\data\\hello.json'
}

But I have made this directory.但是我做了这个目录。 screenshot of the filesystem used in project how do I fix this problem?项目中使用的文件系统的屏幕截图我该如何解决这个问题?

You should use the address this way:您应该这样使用地址:

import * as fs from 'fs'

export default function handler(req, res) {
    fs.readFile("data/hello.json", (err,data)=>{
        console.log(data)
    })
    res.status(200).json({"name" : "Shivam Bhai"})
}

It's always a good idea to also use __dirname for addressing like below:也使用__dirname进行寻址总是一个好主意,如下所示:

import * as fs from 'fs'

export default function handler(req, res) {
    fs.readFile(__dirname + "/../../data/hello.json", (err,data)=>{
        console.log(data)
    })
    res.status(200).json({"name" : "Shivam Bhai"})
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM