Reputation: 41
I'am trying to create a server that can host files. This server chould run on a normal computer with windows, and i shold be able to transfer his files to another computer.
I alredy can transfer files that are text based: .txt, .html, .js, but doesnt work to transfer images: .png, .jpg
I tryed with fs.readFile and fs.load but the result is the same.
server.js
const http = require('http');
const fs = require('fs');
var port = process.argv[2];
http.createServer((request, response) => {
console.log('new connection');
request.on('data',(data)=>{
let c = JSON.parse(data);
switch(c.todo[3]){
case 'downFile':
if(c.todo[4]&&c.todo[5]){
let src = c.todo[4];
let readStream = fs.createReadStream(src);
readStream.once('error',(err)=>{
console.log(err);
response.write(JSON.stringify(err));
response.end();
});
//console.log(readStream);
readStream.once('end',()=>{
console.log('copy done');
response.end();
});
readStream.pipe(response);
}else{
response.write(JSON.stringify('Need to specify the name of the file'));
response.end();
}
break;
default:
//console.log('chexk');
response.write(JSON.stringify('Unknown command'));
response.end();
break;
}
// response.write('success');
})
}).listen(port);
console.log('App Running');
client.js
var request = require('request');
var fs = require('fs');
var port = process.argv[2];
var path = process.argv[3];
var data = {
json:{
todo: process.argv
}
}
var url = 'http://localhost:'+port;
request.post(url,data,(err,res,body)=>{
if(err)console.log(err)
else{
fs.writeFile(process.argv[5]+process.argv[4],body,(err)=>{
if(err)console.log(err);
})
}
})
To start the server I use:
node server.js port
and to make the tranfer i use:
node client.js port downFile inputPath outputPath
Sorry about the english :/
Upvotes: 4
Views: 420
Reputation: 1639
One possible explanation for the discrepancy between text and non-text file transfers is the Content-Type
header of the resource. Especially because you are creating a lower-level server through http
rather than a higher-level service like express
, you need to be careful to set an appropriate Content-Type
for the content being transferred. You can likely extrapolate based off of file extension.
For more information on the HTTP Content-Type
header, check out the MDN documentation
Upvotes: 1