du7ri
du7ri

Reputation: 342

Nodejs TypeError: Busboy is not a constructor

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> 

Upvotes: 2

Views: 3037

Answers (2)

芒果桠
芒果桠

Reputation: 11

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

Upvotes: 1

Islam Babaev
Islam Babaev

Reputation: 46

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?

Upvotes: 0

Related Questions