DEV Community

Cover image for Upload File di Node JS
Juan Angela Alma
Juan Angela Alma

Posted on

Upload File di Node JS

Apa itu Node JS?
Node JS merupakan run time environment pada javascript yang didesain untuk membuat aplikasi website menggunakan bahasa pemrograman javascript. Pada jaman dahulu javascript dikenal sebagai bahasa pemrograman yang berjalan di sisi client, namun sekarang javascript dapat berjalan di sisi server

Apa saja yang akan kita butuhkan?

  1. Node JS
  2. Package Manager (npm, yarn, etc)
  3. Text editor
  4. Formidable

Step 1
Install package formidable

npm install formidable
Enter fullscreen mode Exit fullscreen mode

Step 2
Buat form.html di dalam folder project node js. Form ini akan digunakan untuk field upload file

<form action="upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit">
</form>
Enter fullscreen mode Exit fullscreen mode

Step 3
Buat server.js yang akan menjadi server untuk upload file

const http = require('http')
const formidable = require('formidable')
const fs = require('fs')

const server = http.createServer((req, res) => {
  if(req.url == '/upload') {
    const form = new formidable.IncomingForm()
    form.parse(req, (err, fields, files) => {
      const oldPath = files.file.path
      const newPath = './files/'+files.file.name
      fs.rename(oldPath, newPath, (err) => {
        if(err) throw err
        res.write('File uploaded')
        res.end()
      })
    })
  } else {
    fs.readFile('./form.html', 'utf8', (err, data) => {
      if(err) throw err
      res.writeHead(200, {'Content-Type': 'text/html'})
      res.write(data)
      res.end()
    })
  }
})

server.listen(8080, () => {
  console.log('server running at 8080')
})
Enter fullscreen mode Exit fullscreen mode

yang terakhir jangan lupa untuk membuat folder file yang digunakan untuk menyimpan file yang telah diupload

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series