Is there a possible workaround for the restriction on temporary downloads by Heroku?

When my app starts, I aim to download images from MongoDB for faster performance and local access within the application. However, I encounter crashes on Heroku. How can I address this issue?

Here is the code snippet I am attempting to implement:

dir = "./public/media/"
    function getAllImages() {
        Image.find({}, function (err, allImages) {
            if (err) {
                console.log(err);
            } else {
                allImages.forEach(file => {
                    fs.writeFile(dir + file.name, file.img.data, function (err) {
                        if (err) throw err;
                        console.log('Successfully saved!');
                    });
                });
            };
        });

I currently possess 24 images totaling around 10 MB. These images will serve as static assets in my application, accessible through example.com/media/foo.jpg, among others.

Answer №1

Storing user uploads on Heroku's ephemeral filesystem is not recommended. Any changes made will be lost when your dyno restarts, which occurs frequently (at least once per day). Heroku suggests using a service like Amazon S3 to store uploaded files.

You can allow users to upload files directly from their browsers to S3 or utilize the AWS SDK to save files from your back-end. Consider using a higher-level library such as `multer-s3` for added convenience.

While storing files in your database is generally discouraged, you can instead store a reference to the file location in your database. For instance, saving `https://domain.tld/path/to/some/image.jpg` in your database can serve as a pointer to the actual file location.

Answer №2

It recently came to my attention that the issue stemmed from an empty folder I was using (./public/media). Although it existed in the git system, Heroku failed to create the necessary folder due to its emptiness. Consequently, the line of code

fs.writeFile(dir + file.name, file.img.data, function (err)
was unable to execute properly. Appreciative of all the helpful responses.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Favicon not appearing correctly on various browsers due to unusual source path. Problem observed on React and Express Server configuration

I have deployed a react application on an express server using Heroku. Strangely, the favicon appears when I view the app locally, but does not show up once deployed. The file is returning a status 200, however, when I check the src link, it shows double ...

Node.js server crashes unexpectedly

Hey there, I'm reaching out for some assistance with my project. I am trying to showcase Rainbow Six statistics using this API: https://www.npmjs.com/package/rainbowsix-api-node I have set up a Node server and Express, along with a React frontend. Ho ...

Challenges with file types in the build directory of a React Express application

My website was running smoothly until yesterday, but now I am encountering some issues. It is a React app built with Express and NodeJS. While the website works fine in development mode using yarn start, I am facing errors in production: GET https://www.m ...

The HTML view is unable to display the CSS style due to a MIME-type error

I have recently developed a very simple Express app that is supposed to display a single view called home.html from the view directory. Although the home.html file is being shown, none of the CSS styles I added seem to be loading. The console is throwing t ...

What is the best way to test the SSM getParameter function using Jasmine?

Is there a way to effectively test this? const ssmParameterData = await ssm.getParameter(params, async (error, data) => { if (error) throw error; return data; }).promise(); I have attempted mocking the method by doing: spyOn(ssm, 'getParameter& ...

Getting an error message like "npm ERR! code ENOTFOUND" when trying to install Angular CLI using the command "

Currently, I am eager to learn Angular and have already installed Node version 18.13.0. However, when attempting to install Angular CLI using the command npm install -g @angular/cli, I encountered an issue: npm ERR! code ENOTFOUND' 'npm ERR! sys ...

What is the process for integrating an extension function into an Express response using TypeScript?

I am looking to enhance the Response object in Express by adding custom functions. Specifically, I want to introduce a function: sendError(statusCode: number, errorMessage: string) which can be called from anywhere like this: response.sendError(500, &qu ...

Passport JS fails to pass req.user data to Angular Controller

Currently, I am in the process of developing an application that utilizes an Express/Node backend along with Angular JS for the front end. This stack is fairly new to me, and I have been struggling with retrieving data in an Angular Service + Controller. ...

What could be causing my LESS files not to compile properly in grunt?

I've successfully installed npm and ran npm init. Additionally, I've installed the following packages using npm: grunt grunt-contrib-less grunt-contrib-watch jit-grunt --save-dev My Gruntfile.js configuration looks like this: module.exports = f ...

Intentionally introduce discrepancies in the errors during validation of an object using hapi/joi

const validationSchema = Joi.object().keys({ Id: Joi.number().required(), CustomerName: Joi.string() .trim() .required() .when('$isInValidCustomer', { i ...

Is it possible to store the socketid in order to avoid generating a new one in Socket.io?

When a connection is established with the socket.io server, a unique socket.id is assigned for that connection. If the socket connection remains inactive for some time, a new socket id will be generated. Many tutorials focus on basic "hello world" connect ...

Document is not defined in the Browserify environment

Recently, I came across browserify and was quite impressed. However, when attempting to append a canvas element to my body in a file called Renderer.js, I encountered the following code: window.document.body.appendChild(this.canvas) module.exports = Rende ...

Encountering a pair of errors while working with Node.js and Express

(Apologies for the vague title) I have been developing a project using Firebase and Express, but I am encountering some issues. src/index.js import { initializeApp } from "firebase/app"; import { doc, getFirestore } from "firebase/firesto ...

Tips for efficiently adding a like feature to a MEAN web application

Currently, I am in the process of developing a web application that allows users to express their preferences by liking certain choices displayed on the page. I am trying to optimize the efficiency of the like/unlike system. My main question is whether ev ...

Tips for ensuring that the toJSON method in Sails.js waits for the find operation to complete before returning the object

When I try to run a find inside the toJSON function in the model, the object is returned before the find completes. How can I ensure that the return happens only after the find operation has completed? toJSON: function() { var obj = this.toObject(); Com ...

The online azure code editor for bot seems to be malfunctioning

In the past week, I have been working in the Azure online code editor without any issues. However, today, it suddenly displayed an error stating "There was an issue running a git operation. Please use the console to check the state of your repository." Whe ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

The call is not being answered by the server route (NodeJS + express)

I have encountered an issue while setting up a server using NodeJS and Express. When I attempt to make a get request to the basic route ('http://localhost:3000/'), the request seems to hang indefinitely. Despite thoroughly reviewing my code multi ...

Top Method for Connecting Numerous Dependent HTTP Requests Without the Need for Multiple Subscriptions and Iterations

I'm working on an angular project where I have an API that creates a line item and then loops through to call the API for each modification before firing the print request. Currently, I am using multiple subscribes for this process and I was wondering ...

The efficiency of a for loop in Javascript can be influenced by the way the loop

I experimented with three different for loop cases in JavaScript, each performing a seemingly useless action 1000000000 times. Surprisingly, the speed of these codes varied from one another. Initially, I suspected that the difference in performance could ...