Unresolved function or method for pipe() - node.js

I'm trying to write a simple file web file server. I'm using PhpStorm.
var http = require('http');
var fs = require('fs');
function send404Request(response) {
response.writeHead("404", {"Content-Type": "text/html"});
response.write("404 Page Not Found");
response.end();
}
function onRequest(request, response) {
if (request.method === 'GET' && request.url === '/') {
response.writeHead("200", {"Content-Type": "text/plain"});
fs.createReadStream("./index.html").pipe(response);
} else {
send404Request(response);
}
}
http.createServer(onRequest).listen(8888);
console.log("file server is now running...");
However, PhpStorm says "unresolved function or method pipe()"
Here is my setting for JavaScript libraries in PhpStorm:
Any idea where goes wrong?

In Settings/Project Settings/JavaScript/Libraries, Download "node-DefinitelyTyped". This work for me. I had the same issue as your.

In the end of 2019 faced the same issue but in my gulpfile.js.
i got the "Unresolved function or method pipe()" and
the "Unresolved function or method require()" error messages in PHPStorm.
Downloading the #types/gulp library in PHPStorm resolved both issues.

Perhaps you need to wait for the stream to open:
var readStream = fs.createReadStream("./index.html");
readStream.on('open', function () {
readStream.pipe(response);
});
Additionally, add this to catch any errors that might be going on:
readStream.on('error', function(err) {
console.log(err.message);
});

Here is a workaround I am using. Instead of
fs.createReadStream("./index.html").pipe(response);
I am using:
response.write(fs.readFileSync("./index.html"));
This works well for intelliJ IDEA.

Related

Can I response file Node to React

Is it possible to create a rest api responsing an image file using node? Wondering if there is a proper way to do this.
I have studying fs module to find something.
you can do it
var fs = require('fs'),
fs.readFile(__dirname + req.url, function (err,data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
});
For more details see here

NodeJS - Check whether a SFTP remote file exists using "Sequest"

I'm new to NodeJS and I'm using "Sequest" package for reading contents of a SFTP remote file. It works great. However if the file that I'm trying to read, does not exist, then it throws exception and the app does not respond further.
So I want to check whether the file exists before trying to read it. Since I'm using a library function (sequest.get), I'm unable to handle the exception that occurs in the library method due to absence of the file specified.
Below is my code:
var reader = sequest.get('xyz#abc', fileName, opts);
reader.setEncoding('utf8');
reader.on('data', function(chunk) {
return res.send(chunk);
});
reader.on('end', function() {
console.log('there will be no more data.');
});
Ref: https://github.com/mikeal/sequest#gethost-path-opts
Sequest (https://github.com/mikeal/sequest) is a wrapper to SSH2 - (https://github.com/mscdex/ssh2).
Any help is greatly appreciated. Thank you.
You can listen to error event to handle such cases.
var reader = sequest.get('xyz#abc', fileName, opts);
reader.setEncoding('utf8');
reader.on('data', function(chunk) {
return res.send(chunk);
});
reader.on('end', function() {
console.log('there will be no more data.');
});
reader.on('error', function() {
console.log('file not found or some other error');
});

nodejs expressjs http empty server reply

I have the following backend http endpoint implemented with NodeJS and expressJS
app.get("/api/stocks/lookup/:qry", function(req, res) {
getJson(lookupSearch(req.params.qry), function(json) {
var quotes = [];
und.forEach(json, function(d) {
getJson(quoteSearch(d.Symbol), function(j) {
quotes.push(j);
if (json.length == quotes.length) {
res.send(quotes);
}
});
});
});
});
var getJson = function(search, cb) {
http.request(search, function(response) {
var raw = '';
response.on('data', function(d) {
raw += d;
});
response.on('end', function() {
cb(JSON.parse(raw));
});
response.on('error', function(err) {
console.error(err);
});
}).end();
};
What I do not understand is why this only works sometimes and why other times I get this error message from curl: curl: (52) Empty reply from server My solution that checks the lengths of json and quotes seems correct to me and so I think I must have misused some library. However, as I am new to asynchronous code (the http request in getJson) I am not 100% sure this is correct.
I asked a question with similar code here: syntax and methods for placing callbacks in nodejs Note that the 'homebrewed' solution with incrementing and decrementing a count only works sometimes as well. I do not want to use JQuery inside node either.
Why does the above http request only work sometimes?

node.js: confusion with order of callbacks

I have just started with node.js. I find the asynchronous coding style it uses to be very impressive indeed. However, for those of us who are used to Java and Python it does take some time to get used to it.
I know the following code works fine. This is verified by several questions on this forum. I have also tried it on my own.
var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
//throw err;
}
http.createServer(function(request, response) {
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.write("Other things");
response.end();
}).listen(3000);
});
The way I am interpretting this is as follows:
1. Try reading the html file
i. When done create a server
ii. Send it over to the client
2. Do everything else.
However, we can also have a chain of thoughts as follows:
1. Create the server
2. Try reading the file
i. When done. Send it over to the client
3. In the meanwhile do anything else the server might be asked to do.
The code corresponding to the second chain of thoughts is:
var http = require('http'),
fs = require('fs');
http.createServer(function(request, response) {
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
fs.readFile('./index.html', function (err, html) {
if (err) {
//throw err;
}
response.write(html);
response.write("Other things");
});
response.end();
}).listen(3000);
While the first code works as expected. The second one displays nothing at all in the browser.
Why is the second chain of thoughts wrong?
Actually, what happens here is that the following function gets called each time there is an incoming request:
function(request, response) {
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.write("Other things");
response.end();
}
You replaced that with:
function(request, response) {
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
fs.readFile('./index.html', function (err, html) {
if (err) {
//throw err;
}
response.write(html);
response.write("Other things");
});
response.end();
}
Now here, it will run the following:
Write the header
Queue the readFile
Immediately execute the following: response.end();
By the time it is done reading the file and wants to write the contents, you already ended the response

Writing PDF to a browser failing in Nodejs

I'm trying to read a PDF from a URL and display it to a user's browser (via the passed in 'response' object). I've tried to use the code below and it works sometimes, but generally fails:
function writePdfToBrowser(url, response) {
http.get(url, function(res) {
logger.verbose('about to start download...');
var chunks = [];
res.on('data', function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
logger.verbose('downloaded');
var buffer = new Buffer.concat(chunks);
//write downloaded pdf to the original response
response.write(buffer);
//response.send(buffer);
response.end();
});
}).on("error", function() {
logger.error("error!");
});
}
In the new page where I attempted to load the pdf it would just say "Failed to load pdf".
I'm new to Node, so not sure where the problem lies, any ideas? Anyone have any working code to do the same thing?
Thank you for any help!
Mark
Use piping:
function pipe(url, res) {
var request = http.get(url, function(response) {
res.writeHead(response.statusCode, response.headers)
response.pipe(res);
});
request.on('error', function(error){
res.statusCode = 500;
res.end(error.message);
});
}
... and please provide next time more information about what and how it fails, some logs, inspect response im browser before. And so on..

Resources