Trying to write a file, an internal error occurs

My first experience working with server static files. Something went wrong. How can I understand what’s going on?

Main goal: my goal is to create and read a file from the netlify server

My trying to do this:

http get https://nextjsstart.netlify.app/api/hello?filename=testGondo2

Response: Internal Server Error

localy: work fine

My guess is to use edge functions, on the topic anyway created

src/pages/api/hello.js

import path from "path";
import fs from "fs";
import moment from "moment";

const filesDirectory = path.join(process.cwd());
const dir = `${filesDirectory}/service-data`;

const createFile = (filename) => {
    const fullName = `${dir}/${filename}`;
    if (fs.existsSync(fullName)) {
        return fs.readFileSync(fullName, { encoding: "utf8", flag: "r" });
    }
    const content = `File: ${filename} - created at ${moment().format(
        "MMMM Do YYYY, h:mm:ss a"
    )}`;
    try{
        fs.writeFileSync(fullName, content, { encoding: "utf8" });
        return content;
    }
    catch(err){
        return "Error: " + err.message
    }

};

const operateFiles = (filename) => {
    if (fs.existsSync(dir)) {
        return createFile(filename);
    } else {
        fs.mkdirSync(dir);
        return createFile(filename);
    }
};

export default async function handler(
    req,
    res
) {
    const { filename } = req.query;

    res.status(200).json({ data: operateFiles(filename) });
}

i create netlify function =) ehh i love experiments soo much

http post:

    axios
        .post("https://nextjsstart.netlify.app/.netlify/functions/file-read-write", {
            filename: "hello111",
        })
        .then(({ data }) => {
            console.log(data);
        })
        .catch((err) => {
            console.log(" Error:", err);
        });

result: EROFS: read-only file system, mkdir ‘/var/task/service-data’

netlify/functions/file-read-write.js

const path = require("path");
const fs = require("fs");
const moment = require("moment");

const filesDirectory = path.join(process.cwd());
const dir = `${filesDirectory}/service-data`;

const createFile = (filename) => {
    const fullName = `${dir}/${filename}`;
    if (fs.existsSync(fullName)) {
        return fs.readFileSync(fullName, { encoding: "utf8", flag: "r" });
    }
    const content = `File: ${filename} - created at ${moment().format(
        "MMMM Do YYYY, h:mm:ss a"
    )}`;
    try {
        fs.writeFileSync(fullName, content, { encoding: "utf8" });
        return content;
    } catch (err) {
        return "Error: " + err.message;
    }
};

const operateFiles = (filename) => {
    if (fs.existsSync(dir)) {
        return createFile(filename);
    } else {
        fs.mkdirSync(dir);
        return createFile(filename);
    }
};

exports.handler = async (event) => {
    console.log("handler run")
    try {
        if (event.httpMethod !== "POST") {
            return {
                statusCode: 405,
                body: "Method Not Allowed",
                headers: { Allow: "POST" },
            };
        }
        const data = JSON.parse(event.body);
        if (!data.filename) {
            return {
                statusCode: 422,
                body: "filename are required.",
            };
        }
        const filename = data.filename;
        const body = operateFiles(filename);
        return { statusCode: 200, body };
    } catch (err) {
        console.log(err)
        return { statusCode: 500, body: err.message };
    }
};

i love this game

Yup, all of that makes sense! Perhaps you aren’t aware, but there are no “servers” at Netlify - nowhere your code “runs” on our infrastructure.

That code runs in an AWS lambda, and that lambda runs in a linux container (perhaps not quite the right word, but accurate enough for our purposes). The container is spun up to start the request, and then removed when the request completes. So, the file system is not able to be written on directly, and even if it was…it wouldn’t help you, since you could not “later” access that file (except in the exact same request you wrote it. And why would you want to do that? Write to a file and read it back and then throw it away?)

Check out jamstack.org where we explain the philosophy behind our service and this ecosystem. If you want to save some data while people browse your site, you’ll want to connect to some datastore like faunadb to do any kind of persistent/actually useful data storage :slight_smile:

1 Like

Thank you for answer, i understand. I try make cache. I understand that there are alternatives such as: server variables - but you can’t save a lot here, databases - you need to make a request to them, and if I need a variable that can easily be found by file name, it would shorten the request time. And besides there is 100GB of space that needs to be filled with something. It is a pity that there is no access to the file system, I will use external storage

Note that, you can write files to /tmp directory on Lambda, but as fool mentioned, it’s gone after the response is returned.

Are you talking about 100 GB bandwidth? That has nothing to do with storage space, we do not limit the storage space consumed by a website.

1 Like