[英]NextJs app error while creating Api Routes import * as fs from 'node:fs/promises'; SyntaxError: Cannot use import statement outside a module
I want it to read the json in utf format and display in terminal我希望它以 utf 格式读取 json 并在终端中显示
import * as fs from 'node:fs';
export default function handler(req, res) {
fs.readFile("/blogdata/how-to-learnjavascript.json","utf-8",(err,data)=>{console.log(data)})
res.status(200).json({ name: 'John Doe' })
}
If You want to use fs
module in Next.js
.You can only do FS-related operations while on the server, within getStaticProps
or getServerSideProps
如果您想在
Next.js
中使用fs
模块。您只能在服务器上的getStaticProps
或getServerSideProps
中执行与 FS 相关的操作
Here You Have simple example how to use fs
and path
module with getStaticProps
:在这里,您有一个简单的示例,如何将
fs
和path
模块与getStaticProps
一起使用:
index.js (home page) index.js (主页)
import fs from "fs";
import path from "path";
export default function Home({ data }) {
const persons = data.persons;
return (
<div style={{ padding: 30 }}>
<h1>Example Next.js & Node.js FS module</h1>
<div>
{persons.map((person) => (
<div
key={person.id}
style={{ padding: 20, borderBottom: "1px solid #ccc" }}
>
<h2>{person.name}</h2>
<p>{person.email}</p>
</div>
))}
</div>
</div>
);
}
export async function getStaticProps(context) {
const dataFilePath = path.join(process.cwd(), "data.json");
const fileContents = fs.readFileSync(dataFilePath, "utf8");
const data = JSON.parse(fileContents);
console.log(data);
return { props: { data } };
}
data.json数据.json
{
"persons": [
{
"id": 1,
"name": "dolores",
"email": "dolores@gmail.com"
},
{
"id": 2,
"name": "ed",
"email": "ed@yahoo.com"
},
{
"id": 3,
"name": "james",
"email": "james007@yahoo.com"
},
{
"id": 4,
"name": "joda",
"email": "joda-jedi@gmail.com"
}
]
}
Output( server side ) folder and file structure :输出(服务器端)文件夹和文件结构:
Output browser :输出浏览器:
Tested with "next": "12.1.6"用“下一个”测试:“12.1.6”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.