2

I am working through some tutorials to build a chat server with file upload. I have no prior experience with NodeJS I have been following along with the instructor's code, but recently hit a snag that I cannot resolve. When trying to build the project to run test scripts via npm run dev, I get the following error. it want to recive that the file is uploaded into the uploads folder in my project :

Console log code:

TypeError: Busboy is not a constructor
    at C:\Users\xxx\Desktop\chat\server.js:24:20

in chrome Dev tools

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

answers i found online seems that i have to change the code and i have to call this instead:

const busboyCons = require('busboy');
...
var busboy = busboyCons({ headers: req.headers });

source: https://gist.github.com/shobhitg/5b367f01b6daf46a0287

i also runned this but it dont worked for me. Any help resolving this error would be greatly appreciated -- I'm kind of stuck with it.

server.js:

const express= require('express');
const app= express();

const path = require('path');
const http= require('http').createServer(app);
const PORT=process.env.PORT || 3000;
const io=require('socket.io')(http);
const fs = require('fs');
const Busboy = require('busboy');

app.use(express.static(__dirname + '/public'))
app.use(express.static('uploads'))

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
  });
  
  app.get('/css/main.css', function(req, res) {
    res.sendFile(__dirname + "/public" + "/style.css");
  });

  app.post('/upload', function(req, res) {
    const busboy = new Busboy({ headers: req.headers });
    req.pipe(busboy);
    busboy.on('file', ( fieldname, file, filename) => {
      const ext = path.extname(filename);
      const newFilename = `${Date.now()}${ext}`;
      req.newFilename = newFilename;
      req.originalFilename = filename;
      const saveTo = path.join('uploads', newFilename);
      file.pipe(fs.createWriteStream(saveTo));
    });
    busboy.on('finish', () => {
      res.json({
        originalFilename: req.originalFilename,
        newFilename: req.newFilename
      });
    });
  });


  io.on('file', f => {
    console.log(`File by: ${f.userName}`);
    socket.emit('file', f);
 });


client.js:

const socket = io()


let textarea=document.querySelector('#textarea')
let messageArea= document.querySelector('.message_area')
let formAreaFileUpload=document.querySelector('.submitMediaFiles')
let formSubmit=document.querySelector('#form')

// preventDefault();


formSubmit.addEventListener("submit",handleFormSubmit)

function handleFormSubmit(e) {
    e.preventDefault();

    console.log(e)
    const form = $(this);
    const formData = new FormData(form[0])
    for (const p of formData) {
      if (p[1].size <= 0) {
        return
      }
    }
    $.ajax({
      method: 'POST',
      data: formData,
      cache: false,
      contentType: false,
      processData: false,
      url: '/upload',
      success: handleUploadSuccess,
    })
  }


  function handleUploadSuccess(resp) {
    socket.emit('file', { userName, file: { url: `/${resp.newFilename}`, filename: resp.originalFilename } });


  }

index.html (cutout):

<form id="form" style="background-color: #999999">
            <div class="contentLine">
              
            <div class="column">
              <input id="data" type="file" name="file" />
            </div>
          <div class="column last">
            <button style="float:right" type="submit">Send Multimediafile </button>
           
        
          </div>
            </div>
          </form>
        


    </section>

    <script src="/socket.io/socket.io.js"></script>
    <script src="/client.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> 
2
  • did you ever find a solution for this? Commented Apr 27, 2022 at 18:21
  • Have you figured out this issue? I am using typescript and earlier I thought it could be typing problem but it is something else. busboy: 1.0.0 @types/busboy: ^1.5.0 NodeJs: 14.19.3 Commented Sep 1, 2022 at 1:02

2 Answers 2

1

You can try lowering the version to 0.3.1, npm i [email protected]. I just lowered the version.

Sign up to request clarification or add additional context in comments.

Comments

0

According to the documentation you should use busboy in this way:

const busboy = require('busboy');
const bb = busboy({ headers: req.headers });

But you said you tried and it didn't work. What error occurred then?

5 Comments

hi, it also said that busboy isnt a constructor, i got the tutorial from: iabhishek.dev/post/…
Hi, this is strange because I don't have an error. What version of busboy are you using?
Version 1.5.0, does it uploads in your example, a picture into the uploads folder?
What version are you using ?
1.5.0 version too. No, I just tested the busboy package, here is the source: stackblitz.com/edit/node-hvyrlt You can run the code and see that different error is displayed than "Busboy is not a constructor"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.