how i can send file for that the server read it with fs.createwriteStream();
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
// This opens up the writeable stream to `output`
var writeStream = fs.createWriteStream('./output');
// This pipes the POST data to the file
req.pipe(writeStream);
req.on('end', function () {
res.end('ok upload file');
});
// This is here incase any errors occur
writeStream.on('error', function (err) {
console.log(err);
});
}).listen(8080);
i use this command with console linux:
curl --upload-file hello.txt 127.0.0.1:3000 and work ok but i don't know how send file with url
somebody know?
curl -i -F name=test -F filedata=#localfile.jpg 127.0.0.1:3000
Related
I need to create a node.js app that connects to this ftp server and downloads files from this directory:
ftp://www.ngs.noaa.gov/cors/rinex/2021/143/nynb
I've tried following the ftp npm package docs but I feel like I am doing something horribly wrong:
import Client from "ftp";
/**
* https://github.com/mscdex/node-ftp
*/
const c = new Client();
c.on("ready", function () {
c.get(
"ftp://www.ngs.noaa.gov/cors/rinex/2021/143/nynb",
(error, stream) => {
if (error) throw error;
console.log(`stream`, stream);
stream.once("close", function () {
c.end();
});
}
);
});
// connect to localhost:21 as anonymous
c.connect();
When I run npm run dev with nodemon I get:
Error: connect ECONNREFUSED 127.0.0.1:21
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
[nodemon] app crashed - waiting for file changes before starting...
Can someone please help? I'm completely stumped.
Is it possible if someone could show me a small example of how I can connect to this remote ftp server?
There are a few points :
You're connecting to the local ftp with c.connect();. You need to connect to www.ngs.noaa.gov to download files from there.
This path cors/rinex/2021/143/nynb is a directory on the remote host. c.get doesn't work, you need to list all files in the directory then download them 1 by 1.
The code below connect to the remote server and list all files in the directory
const Client = require('ftp');
const fs = require("fs");
const c = new Client();
c.on('ready', function () {
c.list( "/cors/rinex/2021/143/nynb", function (err, list) {
if (err) throw err;
console.dir(list);
});
});
c.connect({
host: "www.ngs.noaa.gov",
});
hello I'm using docker and ansible to launch a container which will then launch a server.js file, which needs to display the contents of an index.html file located in the same directory. I have this skeleton outline code which works in displaying "Hello World" to the screen when I curl the ip address running this server.js file
var http = require('http');
http.createServer(function (request, response)
{
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8080);
console.log('Server started');
the console.log does not display on the screen, seemingly only response.end does that, with printing 'Hello World' to the screen, so I've been trying to read in the index.html file as a variable and have response.end display it but with no luck.
I tried doing this:
var http = require('http');
http.createServer(function (request, response)
{
response.writeHead(200, {'Content-Type': 'text/plain'});
var fs = require('fs');
var readStream = fs.createReadStream('index.html');
readStream.pipe(response);
//response.end('Hello World\n');
}).listen(8080);
console.log('Server started');
but when I tried to curl it it resulted in a an Error 52 empty reply from the server, am I not doing enough to read in my index.html file and store it as a string variable? thanks.
var http = require('http');
var fs = require("fs");
http.createServer(function(req, res) {
fs.readFile("index.html","utf8" ,function(err, contents){
console.log(contents);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(contents);
res.end();
});
}).listen(3000);
if you want to show the contents of the file on request to the server try this.
I try to create a server, which can receive a file from an HTTP request.
I use Postman as user agent and I add a file to the request. This is the request:
POST /getfile HTTP/1.1
Host: localhost:3000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Cache-Control: no-cache
Postman-Token: 9476dbcc-988d-c9bd-0f49-b5a3ceb95b85
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="test.xls"
Content-Type: application/vnd.ms-excel
------WebKitFormBoundary7MA4YWxkTrZu0gW--
But when the request reaches the server I can not find the file in it (I mean in the request).
I tried to receive it from the body part of the request, but it returned > {} <. I tried to figure out, how can I refer to the name of the file, but unfortunately I can not find any reference in the request header for the name of the file...
Can anybody help me to find out, what should I do?
As a follow up to my comment, you can use the multer module achieve the thing that you want:
https://www.npmjs.com/package/multer
const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer();
app.post('/profile', upload.array(), function (req, res, next) {
// req.body contains the text fields
});
var app = require('express')();
var multer = require('multer');
var upload = multer();
app.post('/your_path', upload.array(), function (req, res, next) {
// req.files is array of uploaded files
// req.body will contain the text fields, if there were any
});
You need to parse the form data from the request. There are a few packages that solves this problem, notably formidable, busboy (or busboy-connect), parted and flow.
Here's a solution using formidable, it is my preferred solution for things like image uploads because it saves to disk.
If you just want to read the file, you can use one of the other packages above.
Install formidable
npm install formidable --save
Then, in your server, you will have to parse the data from the client:
// Somewhere at the start of your file
var IncomingForm = require('formidable').IncomingForm
// ...
// Then in your request handler
var form = new IncomingForm()
form.uploadDir = 'uploads'
form.parse(request, function(err, fields, files) {
if (err) {
console.log('some error', err)
} else if (!files.file) {
console.log('no file received')
} else {
var file = files.file
console.log('saved file to', file.path)
console.log('original name', file.name)
console.log('type', file.type)
console.log('size', file.size)
}
})
A few things to note:
formidable saves files with new names, you can use fs to rename or move them
you can set form.keepExtensions = true if you want saved files to keep their extensions
I have a very simple web server like this:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('./index.html', 'utf-8', function (err, content) {
if (err) {
res.end('something went wrong.');
return;
}
res.end(content);
});
}).listen(8080);
console.log("Server running on port 8080.")
This renders my index.html without any issues, but if I try to reference another file in my index.html via a script tag for instance, the site just gets stuck, unable to find the file which exists in the server directory.
How can I make those files available to my index.html file?
Please keep in mind that I realize this can be done much more easily with Express but I do not wish to use Express. I am trying to learn how things work behind the scene. Thanks in advance.
You need to make the directory visible to public. Its is recommend to use framework while developing the Node.js application.
Here is the code below to server file without framework.
var basePath = __dirname;
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function(req, res) {
var stream = fs.createReadStream(path.join(basePath, req.url));
stream.on('error', function() {
res.writeHead(404);
res.end();
});
stream.pipe(res);
}).listen(9999);
Refer : Node itself can serve static files without express or any other module..?
I need to get zip from rest call (for simulation I use postman with binary option for post and add a little zip file with folder and html file),during the simulation I want to get the data with express and extract the zip and put in some folder under C drive.
Currently when I run the following program(this is all the code which i've tried) but im getting error
events.js:85
throw er; // Unhandled 'error' event
^ Error: incorrect header check
at Zlib._handle.onerror (zlib.js:366:17)
var express = require('express'),
fs = require('fs'),
zlib = require('zlib'),
app = express();
app.post('/', function (req, res) {
var writeStream = fs.createWriteStream('C://myFolder', {flags: 'w'});
req.pipe(zlib.createInflate()).pipe(writeStream);
});
var server = app.listen(3000, function () {
console.log("Running on port" + 3000)
}
)
in postman header i've added the following
content-Type ----> application/zip
How should I overcome this issue and save the zip ? there is other recommended (zlib)library to get extract and save zip?
zlib is meant to extract gzipped or deflated data, not .ZIP files.
You can use the node-unzip module for those:
var unzip = require('unzip');
...
app.post('/', function(req, res) {
var extractor = unzip.Extract({ path : 'C://myFolder' }).on('close', function() {
res.sendStatus(200);
}).on('error', function(err) {
res.sendStatus(500);
});
req.pipe(extractor);
});
If Postman can't handle uploads like this (as suggested in the comments), you can test using cURL:
$ curl -XPOST localhost:3000 --data-binary #test.zip