Serhiy Serhiy - 1 year ago 146
Node.js Question

how to save file in nodeJs?

I am not sure I do right, but want to make next thing:
csend file via webSocket connection on client side and save in in some directory on server. How to save it using nodejs?

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;


}



and server side, webSocket:

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

Answer Source

For this you have to use fs(File system). code of your node used doe saving the file.

 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!");
        });
    });

Hope this works for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download