Serhiy
Serhiy

Reputation: 1981

How can I save a file in Node.js?

I am not sure I do it right, but I want to make the following thing: Send a file via a WebSocket connection on the client side and save in in some directory on the server. How can I save it using Node.js?

Client side:

<input type="file" id="myFile" multiple size="50" onchange="myFunction()">

<script type="text/javascript">
    console.log('test');

    var socket = new WebSocket("ws://localhost:8081");

    socket.onmessage = function(event) {
        var incomingMessage = event.data;
        showMessage(incomingMessage);
    };

    function showMessage(message) {
        var messageElem = document.createElement('div');
        messageElem.appendChild(document.createTextNode(message));
        document.getElementById('subscribe').appendChild(messageElem);
    }

    function myFunction() {
        var x = document.getElementById("myFile");
        var txt = "";
        if ('files' in x) {
            if (x.files.length == 0) {
                txt = "Select one or more files.";
            } else {
                for (var i = 0; i < x.files.length; i++) {
                    txt += "<br><strong>" + (i+1) + ". file</strong><br>";
                    var file = x.files[i];
                    console.log(file);
                    if ('name' in file) {
                        txt += "name: " + file.name + "<br>";
                    }
                    if ('size' in file) {
                        txt += "size: " + file.size + " bytes <br>";
                    }
                    socket.send(file);
                }
            }
        }
        else {
            if (x.value == "") {
                txt += "Select one or more files.";
            } else {
                txt += "The files property is not supported by your browser!";
                txt  += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
            }
        }
        document.getElementById("demo").innerHTML = txt;
    }
  </script>

And the server side, webSocket:

ws.on('message', function(message) {
    // Here I need to save the file in uploadFile.path = './files/' + 'fileName'
    // and get the file name
});

Upvotes: 4

Views: 26885

Answers (1)

Shekhar Tyagi
Shekhar Tyagi

Reputation: 1674

For this you have to use fs(File system). The code of your Node.js file should be like this:

ws.on('message', function (message) {
    var fs = require('fs');
    fs.writeFile("/tmp/test", message, function (err) {
        if (err) {
            return console.log(err);
        }
        console.log("The file was saved!");
    });
});

Upvotes: 9

Related Questions