Node Js API : where the undefined comes from? - node.js

I write this code to get the array from url. this is the url : http://localhost:3000/main?a=aaa.jpg&a=bbb.jpg
And here is the code :
//Define module
var express = require('express');
var app = express();
const { exec } = require('child_process');
//extract function
function extract (req,res,next){
res.write(`filename : ${req.query.a}`); //kt page
console.log(req.query.a);//kt terminal
next();
};
//main function
function main (req,res,next){
res.write('\nkuor dok \n');
res.end();
};
app.use(extract);
app.get('/main',main);
app.listen(3000);
This is the output in terminal.
Array(2) ["aaa.jpg", "bbb.jpg"]
undefined
The question is where the undefined comes from? It affected everything i need to do. The array is perfectly fine. But suddenly undefined comes out. Can anyone help me. Thank you in advance.

I tried the code you provided above and i got only the array in the terminal
[ 'aaa.jpg', 'bbb.jpg' ]
When i tried the url in the browser i got
filename : aaa.jpg,bbb.jpg
kuor dok
as the output. i didn't get any undefined

I see that you are trying to define extract function as a middleware. It will be executed for every request
try to comment app.get:
app.use(extract);
//app.get('/main', main);
app.listen(3000);
Then try to make the request
GET: http://localhost:3000/main?a=aaa.jpg&a=bbb.jpg
you will get
[ 'aaa.jpg', 'bbb.jpg' ]
You are handling the request twice. First by the global middleware, the second time by app.get() that calls also the middleware extract before main
As I see app.get don't handle your query params and you got undefined due to an empty object try to log: req.query intead of req.query.q
function extract(req, res, next) {
res.write(`filename : ${req.query.a}`); //kt page
console.log(req.query); //kt terminal
next();
};

Related

NodeJS Passing Express res to completely different module

I have an program that susposed to load js to server side dynamically by url (for organizing js files)
app.get('/*',function(req,res){
... path etc. code
if(compare(list,path)){
const js = require('/Js/'+list.find(x => x.pageUrl == path).js)
js.run(req,res)
}
... more code there
}
but for some reason passed res doesnt work and i get res.send is not defined error
here is the other module that i get path from url and load it
exports.run = function run(req,res)
{
res.Send("test") //not defined for some reason
console.log(res) //it is not undefined, i see stuff
res.end()
}
Your code says res.Send instead of res.send.

Node.Js promises and async/await

I am trying to use a oai-pmh harvester to harvest all articles from oai repositor and store them in a local mongo database.
I have a small demo.js file to test and print the titles on the console and it works perfectly. This is my demo.js file:
const oaipmh = require('./my_modules/harvester/harvester.js');
const urlProvider='any OAI URL repo'; // change URL here
let harvester=new oaipmh.Harvester(urlProvider);
harvester.harvest(processItem,function(err,res){
console.log(res);
});
Function processItem(item){
try{
let titles=item.metadata['oai:dc:dc']['dc:title'];
let title=(typeof titles=='object')?titles.join("\n"):titles;
console.log(title);
console.dir(item.metadata['oai_dc:dc']);
}catch(err){
// handle errors here
}
};
I am still trying to learn how to use promises and async/await and how to handle it. So far I have tried to use it inside my controller, but I am getting an error.
On my router file i have:
router.route('/doc')
.get(doc.aggregate_one);
On my controller file i have:
var Doc=require('../models/docModel);
const aoipmh=require('../../harvester/harvester');
exports.aggregate_one = async (req,res,next) => {
const urlProvider = req.header('url');
let harvester=new oaipmh.Harvester(urlProvider);
harveste.harvestAsync(urlProvider,processItemmfunction(err,res){
// do something
});
};
I want to send the URL in the header of my get instead of the barcode. When I am trying to test the GET I am receiving an UnhandledPromiseRejectionWarning: Error; Unexpected status code 400 (expected 200)
How can I use the example of the demo.js file inside my controller in order to handle the Promise?

Node JS : invalid data error using execFileSync

I am stuck on a NodeJS error while trying to execute a script and get the output of it.
I get the following error :
TypeError: invalid data
at WriteStream.Socket.write (net.js:623:11)
at Object.execFileSync (child_process.js:482:20)
at doRender (/test/apps/application/routes/TEST.js:1786:26)
I guess it comes from a misuse of the NodeJS native execFileSync function, but I've tried a lot of things to match the documentation without any success so far.
Here is my code :
router.get("/stat", authReader, function (req, res) {
//Current file is in application/routes
var doRender = function (req, res) {
var output;
//I want to execute application/scripts/test.bash
output= child_process.execFileSync("test.bash",[], {
cwd: "../scripts"
});
result= processDataFromCSV(output);
//processing data in response
res.render(acronym + "_test", {
title: "CSV output",
result: result,
});
}
doRender(req, res);
}
Could you please help me to understand what I am doing wrong ? Any help is greatly appreciated.
Verify that your test.bash is executable, or run it like /bin/bash test.bash using child_process.execSync(). For more information look at this answer by Sravan here;

Nested express app use does not work

When i am doing nested express apps, nested app use does not work
var app = express();
var localApp = express();
app.use('/pdf-exporter', PDFExporterModule());
function PDFExporterModule(app) {
localApp.use(function(req, res, next) {
//this code never execute !!!!!!
next();
});
localApp.get('/subpath/:userId', function() {...});
return localApp;
}
localApp doesn't have a value when you first call PDFExporterModule(). Move var localApp=express() up, or better yet, don't define local app outside of PDFExporterModule.
Also, it's good practice to leave all your var statements at the top. Variable hoisting makes localApp exists and is undefined right at the top of your script. It gets its value though where you have var localApp=express() below.

formidable doesnt work with express

Before you wast any time : please note that this is a reference question , just in case some one needed it. but please feel free to correct me :)
so , im trying to use formidable (i know that it's so similar to bodyParser and that i should be using body parser instead ! ) with express . the problem that it doesnt work at all .
here is simple part of my code (relevant part )
form.on('progress', function (bytesReceived, bytesExpected) {
console.log(bytesExpected);
console.log('progress ');
if (bytesReceived > options.maxPostSize) {
console.log('bla ');
req.connection.destroy();
}
}).on('end', finish).parse(req,function(err, fields, files) {
console.log(files);
});
now if i try to console.log -> err , fields , or files it doesnt work .
an the only event that is being emitted is progress .
if you use app.use(express.bodyParser())
is equivalent to:
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());
the multipart use formidable, so events doesn't trigger,you can remove app.use(express.multipart()); then you can use formidable object.
The problem is caused by the parse function . To solve this you need to not use the bodyParser .
So let's assume that i have a route /files which only recives a post request then you need to disable the bodyParser just for that route like so :
app.use(function(req,res,next){
// important .. this will skip body parser to avoide issues with formidable
if((req.path == '/file' ||req.path == '/file/') &&req.method === 'POST'){
// GET , PUT , DELETE ,etc... will have bodyParser ^^^^^^^^^^^^^^^^^^^^^
return next();
}
express.bodyParser(req,res,next);
next();
});

Resources