set/read file

main
radex 2023-08-15 18:07:40 +02:00
parent f97b100b0d
commit 0a31cb5b21
2 changed files with 68 additions and 9 deletions

View File

@ -1,5 +1,44 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import fs from 'fs'
import path from 'path'
import getConfig from 'next/config';
// const { serverRuntimeConfig } = getConfig();
// console.log({
// env: process.env,
// serverRuntimeConfig,
// })
// TODO: Why don't env variables propagate to here?
// const messagePath = path.join(serverRuntimeConfig.dataPath, 'message')
const messagePath = '/data/message'
function getFileData() {
try {
const data = fs.readFileSync(messagePath).toString()
console.log(data)
return data
} catch (_e) {
return ''
}
}
function setFileData(newMessage) {
try {
fs.writeFileSync(messagePath, newMessage)
} catch (_e) {
console.log(_e)
}
}
export default function hello(req, res) {
res.status(200).json({ server: 'bruh' })
if (req.method === 'PATCH') {
setFileData(req.body.message.slice(0,280))
res.status(202)
} else {
res.status(200).json({
server: 'bruh',
file: getFileData(),
})
}
}

View File

@ -1,5 +1,5 @@
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Head from "next/head";
import styles from "../styles/Home.module.css";
export default function Home() {
return (
@ -8,11 +8,31 @@ export default function Home() {
<title>Create Next App</title>
</Head>
<h1>bruh</h1>
<button onClick={async () => {
const res = await fetch('/api/hello')
const json = await res.text()
alert(json)
}}>bruh?</button>
<button
onClick={async () => {
const res = await fetch("/api/hello");
const json = await res.text();
alert(json);
}}
>
bruh?
</button>
<button
onClick={async () => {
const newMessage = prompt("new bruh?");
await fetch("/api/hello", {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
message: newMessage,
}),
});
}}
>
set bruh
</button>
</div>
)
);
}