Connect-busboy: The file being piped to the write stream is either empty or incorrect, depending on its type

My current project involves testing a file upload feature using connect-busboy. Interestingly, I have encountered a peculiar issue when uploading PNG files - although the file gets uploaded, the content seems to be incorrect and unable to open. Upon further investigation by comparing MD5 checksums of the source and destination files, it appears that they are different. Additionally, when attempting to upload a text file with only 15 bytes of data, I find that it gets uploaded in the ./public/ directory but remains empty.

Of particular interest is the client-side code snippet:

<form method="post" enctype="multipart/form-data" action="/api/upload">
   <input type="file" name="thumbnail"/>
   <input type="submit"/>
</form>

On the server side:

// Some includes may have been omitted for readability
var Busboy = require("connect-busboy");
app.use(Busboy());

// Adding entries to places
app.post("/api/upload", function (req, res, next) {
    req.pipe(req.busboy);
    var filesNames = [];
    req.busboy.on('file', function(fieldname, file, filename) {
        file.on("data", function(data) {

            var fstream = FS.createWriteStream('./public/' + filename,{flags: "a"});
            file.pipe(fstream);
            filesNames.push(filename);
            fstream.on("close", function() {
                console.log("Closing fstream");
            });
        });

    });
    req.busboy.on("finish", function () {
        res.writeHead(200, {'Connection': 'close'});
        for (var i = 0; i < filesNames.length; i++)
        {
              res.write(filesNames[i] + "\n");
        }
        console.log("busboy done");
        res.end("Done..");
    });

});

I have already researched various posts related to busboy, so I made sure to gather information beforehand before asking this question.

As an additional note: When I log the data, I can see the expected bytes coming through, but they do not seem to be successfully written to the file, particularly in the case of .txt files.

What could be the possible mistake I am making here?

Answer №1

If you're receiving multiple pieces of file data, it's best not to create a new writable stream each time. You can optimize your process by reusing the same stream for efficiency.

req.busboy.on('file', function(fieldname, file, filename) {
    var ws = FS.createWriteStream('./public/' + filename, {flags: "a"});
    file.pipe(ws);
    filesNames.push(filename);
});

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

Utilizing window.location.pathname in Next.js for precise targeting

Are you familiar with targeting window.location.pathname in NEXT.JS? I encountered a red error while using this code in Next.js const path = window.location.pathname console.log(path) // I am able to retrieve the pathname here Then { ...

Customize WordPress zerif-lite theme with CSS to decrease page width temporarily

Is there a way to decrease the width of a specific page on my website without modifying the current theme that I am using (zerif-lite)? I want to accomplish this task by adding custom CSS to styles.css. However, I am facing difficulties as I only want to a ...

Insert text within a span tag next to a picture

Greetings everyone, Here is the current structure I am working on: <div class="payment-option clearfix"> <span class="custom-radio pull-xs-left">...</span> <label style="display:inline;width:100%"> <span style="fl ...

What is the best way to extract a number from a string in JavaScript?

There are instances in HTML files where a <p> tag displays the price of a product, such as ""1,200,000 Dollar"". When a user adds this product to their cart, I want the webpage to show the total price in the cart. In JavaScript, I aim to e ...

Maintaining the active state in Bootstrap, even when manually entering a URL, is essential for smooth

Check out this fully functional plnkr example: http://plnkr.co/edit/p45udWaLov388ZB23DEA?p=preview This example includes a navigation with 2 links (routing to 2 ui-router states), and a jQuery method that ensures the active class remains on the active lin ...

Is it possible for a submission of a form to modify the content length header, resulting in the request failing?

Issue Description: After binding a submit event to an AJAX post request in order to send a predetermined key-value pair to a PHP script, the expected message indicating successful communication is not received. Despite the fact that the submit event trig ...

Shifting HTML table in Javascript by toggling checkboxes

When I click the checkbox, the table elements are not displaying inline. I am simply hiding the class "box". Do I need to write a special format? By default, the elements are displayed inline but when I check the checkbox, they shift. The column 'Stat ...

Unable to invoke the jQuery datetimepicker function within a personalized directive

I have created a unique time picker directive in AngularJS to display a datetimepicker. app.directive("timePicker", function() { return { restrict: "A", link: function(scope, elem, attrs) { / ...

Achieving a delayed refetch in React-Query following a POST请求

Two requests, POST and GET, need to work together. The POST request creates data, and once that data is created, the GET request fetches it to display somewhere. The component imports these hooks: const { mutate: postTrigger } = usePostTrigger(); cons ...

Errors encountered during the Angular project build

I need help figuring out what's happening. I keep getting the same error while trying to build my project. I've already attempted deleting typings, angular directory, and performing typings install but nothing seems to be working. All the necess ...

Suggestions for addressing the "required" attribute issue with express-handlebars?

I am currently utilizing express-handlebars and have crafted a home.hbs (home.handlebars) file where everything is functioning correctly except for one specific issue. The "required" attribute is not working as expected, and it is also not being highligh ...

What is the process for implementing a click event and accessing the DOM within an iframe using react-frame-component?

I am working on using the react-frame-component to create an iframe. I am trying to bind a click event on the iframe and retrieve the DOM element with the id of "abc" inside the iframe. Can anyone guide me on how to achieve this? The code snippet provided ...

What is causing myInterval to not be cleared properly?

const homeButton = document.getElementById('home'); window.myInterval = 0; const showHome = () => { console.log('showHome'); window.myInterval = setInterval(wait, 400) } const wait = () => { console.log('wait'); ...

Saving data from Material UI forms in TypeScript

Is there an effective method for storing values entered into the text fields on this page? const AddUserPage = () => ( <div> <PermanentDrawerLeft></PermanentDrawerLeft> <div className='main-content'> < ...

Ensuring the presence of a bootstrap angular alert with protractor and cucumberJS

I am currently utilizing protractor, cucumberJS, and chai-as-promised for testing. There is a message (bootstrap alert of angularJS) that displays in the DOM when a specific button is clicked. This message disappears from the DOM after 6000 milliseconds. ...

Show an image based on a query parameter

Currently, I am developing a PHP project and I am facing an issue with loading an image from a query string. Here is the code snippet I am using: <img src="load_image.php?name=Profile_Photo_Small" /> Is there anyone who can help me out with this pro ...

Discover the ultimate solution to disable JSHint error in the amazing Webstorm

I am encountering an error with my test files. The error message states: I see an expression instead of an assignment or function call. This error is being generated by the Chai library asserts. Is there a way to disable this warning in Webstorm? It high ...

JavaScript for controlling first-person movement with a mouse

Currently, I am working on implementing a first person movement feature using the mouse. While I have successfully implemented it using the keyboard, I am facing challenges with the mouse input. The issue arises from the ambiguity in movement directions ca ...

Launch a new tab within the parent window, passing on variables from the parent window

Currently, I have a button that opens a new window in a new tab by using window.open("newpage.html"). In the child window, I use childVar = window.opener.parentGlobalVar to access global variables from the parent window. Now, I have been requested to open ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...