Create a local file sharing server

Article


author small image Siva Kishore G
Posted : 20 Mar 2023
Modified : 21 Mar 2023
Expert Developers

Introduction

Learning Node JS opens a lot of doors. You can basically create anything. So, I've created a local file sharing server where my employees can share files with each other and keep it only in my local network. Not saying that I have anything against online file storage like dropbox or google drive. Its just that I wanted to create a local file server where the files just sit on my local computer.

In this tutorial, you will learn how to create a local file server that download & upload files and can sync between all computers in the network. Lets get into it, but before we do, I'm assuming you are fluent in ExpressJS, Express-Handlebars, File system and Socket IO.

Local File Sharing Server

See the full code in my Github

Local File Sharing Server

Reserve the Server IP

The first thing we need to do is, binding your computer (Server) MAC address to a predefined local IP address so that the IP address of the server remains the same. To do this, you need to have access to your router and it should have the "IP & Mac binding" functionality available. Or atleast in my case thats what its called and I have a TP Link router. See the image below on how to set it up.

IP & Mac Binding - TP Link Router

Upload Files

For getting the drag and drop upload functionality, I've used FilePond. With this library, we can restrict the file types to be uploaded, file size, preview and lot more with ease. The only downside of this is, we cannot upload by folders, we would have to zip it first and then upload it. Thats the only workaround for now.

var pond = FilePond.create(document.getElementById('fileUploadInput'), {
    server: '/upload',
    onprocessfile: function (err, file) {
        if (!err) {
            setTimeout(function () {
                pond.removeFile(file)
            }, 1000)
        }
    }
});

pond.removeFile(file) will remove the file thumbnail after the upload is complete. Othrewise, it just lingers on the drag and drop element.

I've used express-fileupload package to handle the file uploads. If you want more in-depth knowledge on how to upload and move / manipulate the file contents, refer my article on Upload Image To Node Js Server Using Express-Fileupload

Node JS FileSystem (FS package)

The file system package FS will provide the file contents everytime you load the page. I've created two routes /get-files and /delete-file for getting the upload folder content and delete the files in the folder respectively.

app.get('/get-files', (req,res)=>{
    fs.readdir('files',(err,data)=>{
        if(err) return res.status(503).send("Unable to get the file data")
        var fileObj = {}
        for(var d of data){
            fileObj[d] = fs.lstatSync(`files/${d}`).isDirectory() ? "Directory" : "File"
        }
        res.send(fileObj)
    })
})
app.get('/delete-file',(req,res)=>{
    fs.unlinkSync("files/"+req.query.file)
    res.redirect('/')
})

File / Directory

We need to create some logic to see if the uploaded files folder has directories in it and when fetching the files, we need to notifiy the user that those are directories and not available to download.

app.get('/download',(req,res)=>{
    if(req.query.type === 'File'){
        res.download(`files/${req.query.file}`)
    }else{
        res.send("Download is a folder")
    }
})

Socket IO

For realtime synchronizations, we need to use websockets for which I've chosen Socket IO. Socket IO is a great little library for implementing websockets in a node JS project and even better, an Express Project. Websocket calls are required in three phases,

  1. When the user reload the page
  2. Whenever there is an upload / deletion of files
app.get('/download',(req,res)=>{
    if(req.query.type === 'File'){
        res.download(`files/${req.query.file}`)
    }else{
        res.send("Download is a folder")
    }
})

Conclusion

This project is just into a few versions which lacks in notification / sync when the user removes any file manually. The frontend will not update that. We can overcome that with some sort of periodic file check and which in our case is calling getFiles() function in an setInterval function.



Post a comment

I promise, I keep it clean *

Comments

Alert SVG Cookie Consent

This website uses cookies and similar technologies, to enhance your browsing experience and provide personalized recommendations. By continuing to use our website, you agree to our Privacy policy.