How to write a REST API for nodejs to return a random number? - node.js

In fallowing code which is generating a 5 digits number and I would like to make a single API to call this code and return a random number. something like:
https://sub.mydomain.com/getnumber
function getnumber() {
var code = "";
var possible = "1234567890";
for (var i = 0; i < 5; i++) {
code += possible.charAt(Math.floor(Math.random() * possible.length));
if (i == 0 && code == "0") {
code = "7"
}
}
return code;
}

I am no expert at all but as you get on comments node.js http server is your solution:
try this little one code:
const http = require('http');
http.createServer((request, response) => {
if (request.method === 'GET' && request.url === '/getnumber') {
request.pipe(response);
response.end(getnumber());
} else {
response.statusCode = 404;
response.end();
}
}).listen(8080);
function getnumber() {
var code = "";
var possible = "1234567890";
for (var i = 0; i < 5; i++) {
code += possible.charAt(Math.floor(Math.random() * possible.length));
if (i == 0 && code == "0") {
code = "7"
}
}
return code;
}
your URL should be like:
127.0.0.1:8080/getnumber

Related

reset request queue in node.js vanilla server

I have a program that accepts POST requests with a body that contains numbers. My program checks is the numbers in body are prime numbers or not. Everything is well the first time, but every time after that the program remembers the past POST requests a checks them as well.
how can I reset the request queue so my program will only check the newest POST request?
here is the code:
import { createServer } from "http";
import { parse } from "querystring";
import { url } from "inspector";
import { port } from "./config.js";
let body = "";
let checkNumber = true;
const PORT = process.env.PORT || port;
const server = createServer(async (req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
const FORM_URLENCODED = "application/x-www-form-urlencoded";
const POST_PATH = "api/numbers/prime/validate";
const GET_PATH = "api/numbers/prime";
if (req.headers["content-type"] === FORM_URLENCODED) {
//console.log(req.method);
if (req.method === "POST") {
req.on("data", (chunk) => {
body += chunk.toString();
});
}
if (req.url === `/${POST_PATH}`) {
let re = parse(body);
await checkValuesInObject(re);
console.log(checkNumber);
res.end(`${checkNumber}`);
}
res.end();
});
server.listen(PORT, () => {
console.log(`listening on port ${PORT}`);
});
async function checkIfFirstNumber(number) {
if (number == 1) {
return false;
} else {
for (let i = 2; i < number - 1; i++) {
if (number % i === 0) {
return false;
}
}
return true;
}
}
async function checkValuesInObject(obj) {
const amount = Object.keys(obj);
for (let i = 0; i < amount.length; i++) {
let valueAmount = obj[Object.keys(obj)[i]];
for (let j = 0; j < valueAmount.length; j++) {
checkIfFirstNumber(valueAmount[j]).then((answer) => {
console.log(`answer: ${answer}`);
if (!answer) {
checkNumber = false;
}
});
}
}
checkNumber = true;
}
async function printPrime(number) {
let numbers = "";
for (let i = 2; i <= number; i++) {
const check = await checkIfFirstNumber(i);
if (check) {
numbers += i + " ";
}
}
return numbers;
}

Can't return value from async function in Node.js but console prints the values

I am new to node.js and I read a few posts about this problem but still don't understand how to solve it in my case. The correct result is printed out, but I want it to be returned or be stored in a variable. Is this possible?
const values = async () =>
{
const URL = 'http://www.espn.com/sports/tennis/rankings';
const response = await request(URL);
const $ = cheerio.load(response);
let title = $ ('#my-players-table > div.mod-container.mod-table > div.mod-content > table > tbody').text();
var rank = 1;
var count = title.length;
var words = title;
var player = "";
var players = [];
for ( var i = 70; i < count; i++)
{
if(!characterNumber(words[i]) && words[i] != "\n")
{
player += words[i];
}
else
{
if(player != "" && player != '\n')
{
players.push(player);
player = "";
}
}
}
return players;
};
let playersRankings;
const getRankings = async () => {
playersRankings = await values();
console.log(playersRankings);
}
getRankings();

How can I fix 'Refactor this function to use "return" consistently.' from sonar js

I apply SonarJS analysis to my project.
An error 'Refactor this function to use "return" consistently' was found in the code below.
How can I fix this?
var filter1Depth = function(attr0, attr1, val){
var id;
if(val === "vAuto"){
id = "AirConditioner.Indoor.Ventilator";
val = "Auto";
}
return { // Error is generated from this line.
field : attr0,
operator: function(item, value){
if(value == "") return true;
if(!item || !item.length) return;
var i, length = item.length;
if(value == "undefined"){
for( i = 0; i < length; i++ ){
if(typeof item[i][attr1] === 'undefined'){
return true;
}
}
}else{
for(i = 0; i < length; i++){
if(item[i][attr1] == value){
if(id){
if(id === item[i]["id"]) return true;
return;
}
return true;
}
}
}
return;
},
value : val
};
};
Another example is like below.
var filter1DepthNone = function(attr0, attr1, val){
return { field : attr0, operator: function(item, value){ // error!!
if(value == "") return true;
if(!item || !item.length) return;
var length = item.length;
for(var i = 0; i < length; i++){
if(item[i][attr1] != value){
return;
}
}
return true;
}, value : val};
};
My codes where this error is generated from has similar pattern..
In some blocks, you're returning nothing (return;, so undefined) but in other blocks in the same function, you return a boolean (true/false).
You need to make sure that your returns are consistent within a function - that is, if you return a boolean somewhere, everywhere you return a value within that same function, you also return a boolean.

need to return some data from a function using chrome.storage api

Content.js
function GetFilterfromStore3(document_root) {
var numberdata = 0;
chrome.storage.sync.get("fiterlink", function (filterlist) {
var links = [];
var number = 0;
node = document_root.getElementsByTagName("a");
//alert(filterlist.fiterlink[0].data.link)
for (var i = 0; i < filterlist.fiterlink.length; i++) {
if (filterlist.fiterlink[i].data.selected == true) {
links[i] = filterlist.fiterlink[i].data.link;
}
}
for (var i = 0; i < node.length; i++) {
for (var j = 0; j < links.length; j++) {
if (node[i].getAttribute("href") != null) {
if (node[i].getAttribute("href").indexOf(links[j]) != -1) {
number++;
}
}
}
}
alert(number + " :1");
numberdata = number;
});
return (numberdata);
};
chrome.runtime.sendMessage({
action: "getnumberoflink",
number: GetFilterfromStore3(document),
});
Event.js
chrome.tabs.onSelectionChanged.addListener(function (activeInfo) {
chrome.tabs.executeScript(null, { file: 'Getnumberoflinks.js' });
// Perform the callback when a message is received from the content script
chrome.runtime.onMessage.addListener(function (message) {
if (message.action == "getnumberoflink") {
chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255] });
chrome.browserAction.setBadgeText({ text: message.number.toString() });
}
});
});
I need to get number from content.js in event.js.
i have some filterlist in my chrome storage and after this i am finding links count on page.
but in event.js i get 0
please help me out and comment if you have some confusion.

NodeJS script stucks on multiple queries to the OMBD API

I'm trying to retrieve the data for all the movies in IMDB trough the OMDB API. To achieve this, I made a simple NodeJS script that runs trough all the posible IMDB movie IDs, making an API call for every ID. This IDs have the form ttXXXXXXX, where X is an integer.
The problem is that, if the number of iterations of the for loop is greater than ~2500, the script stucks on the last 3 to 8 queries.
What could be happening? Is it a memory problem given the ammount of iterations?
The script itself is the following:
const http = require('http');
var asyncsLeft = 0; // This is used to track when the final http.request callback is done
var movieCount = 0; // Count the number of movies retrieved
var N = 10000 // Number of iterations
// Callback for the OMBD API call
function callback(res) {
var movieRawData = '';
res.setEncoding('utf8');
// Getting the chunks of data from the API response
res.on('data', (chunk) => {
movieRawData += chunk;
});
res.on('end', function() {
var movieData = JSON.parse(movieRawData)
if(movieData.Type == 'movie') {
console.log(++movieCount + "\t" + movieData.Title);
}
});
res.on('error', function(err) { console.log(err); });
};
for(var i = 0; i <= N; i++) {
// Options for the API call
var options = {
host: 'www.omdbapi.com',
path: '/?i=tt' + idGenerator(i),
method: 'GET',
};
// Making the API call itself and increment the async calls counter
var req = http.request(options, callback);
asyncsLeft++;
req.on('error', function(e){ console.log(e) });
req.end();
};
// Function to generate valid seven digits IMDB's movie ID
function idGenerator(index) {
if (index >= 1000000){ return '' + index; }
else if (index >= 100000) { return '0' + index; }
else if (index >= 10000) { return '00' + index; }
else if (index >= 1000) { return '000' + index; }
else if (index >= 100) { return '0000' + index; }
else if (index >= 10) { return '00000' + index; }
else if (index >= 0) { return '000000' + index; }
}

Resources