I have the url: http://www.localhost:8080/api/numbers/prime?amount=13
via GET request
I want to get api/numbers/prime
is there any way to do that in node.js vanilla?
You can use JavaScript split and slice methods on Strings.
let url = "http://www.localhost:8080/api/numbers/prime?amount=13";
let urlWithoutQuery = url.split("?")[0];
let path = urlWithoutQuery.slice(25); // To get the value after http://www.localhost:8080
You can use URL:
const url = new URL('http://www.localhost:8080/api/numbers/prime?amount=13')
then:
console.log(url.pathname);
// outputs:
// /api/numbers/prime
console.log(url.searchParams);
// outputs:
// URLSearchParams { 'amount' => '13' }
console.log(url.search);
// outputs:
// ?amount=13
Related
I am trying to extract pdf data to json format like below using in adobe pdf extract api,
this is the json I am getting
I want it to be something like this
Tried lots of solution with nested approach but can't figure out a proper way.
I have tried a nested approach but it didn't give proper solution
here is code
`
const fs = require("fs");
// Read the JSON file
const jsonString = fs.readFileSync("structuredData.json", "utf8");
// Parse the JSON string into an object
const data = JSON.parse(jsonString);
// Initialize the output object
const output = {};
// Loop through each line in the data
data.elements.forEach((line) => {
// Get the path and text values
const path = line.Path;
const text = line.Text;
// Split the path into an array
const pathParts = path.split("/");
// Initialize the current object to be the output object
let current = output;
let prev = null;
// Loop through each part of the path
pathParts.forEach((part, index) => {
// If this is the last part of the path, set the text as the value
if (index === pathParts.length - 1) {
if (Object.keys(current)[0]) {
prevdata = current[Object.keys(current)[0]];
current[Object.keys(current)[0]] = { ...prevdata, [text]: {} };
} else [(current[text] = {})];
} else {
// If the current object doesn't have a property with this path part, create it
if (!current[part]) {
current[part] = {};
}
// Set the current object to be the nested object
current = current[part];
}
});
});
// Convert the output object to a JSON string and write it to a file
fs.writeFileSync("output.json", JSON.stringify(output));
`
Consider the following.
node file1.js && react-scripts start
I am trying to make an API call to the GCP Secret Manager in file1.js. After the request is received, I want to set them as environment variables under process.env. After that, I want to access them in the frontend. The browser can't make a call to that Secret Manager without OAuth. Is there any way I can share process.env between these two scripts?
File1 code
const {SecretManagerServiceClient} = require('#google-cloud/secret-manager');
// Instantiates a client
const client = new SecretManagerServiceClient();
const firebaseKeysResourceId = 'URL'
const getFireBaseKeys=async()=> {
const [version] = await client.accessSecretVersion({
name: firebaseKeysResourceId,
});
// Extract the payload as a string.
const payload = JSON.parse(version?.payload?.data?.toString() || '');
process.env.TEST= payload.TEST
return payload
}
getFireBaseKeys()
Expanding on my comment
Method 1 - kind of neat but unneccessary
Supposing you had these vars you wanted in the environment:
const passAlong = {
FOO: 'bar',
OAUTH: 'easy-crack',
N: 'eat'
}
Then at the end of file1.js you would do this
console.log(JSON.stringify(passAlong));
Note you cannot print anything else in file1.js
Then you would call your script like this
PASSALONG=$(node file1.js) react-script start
And at the beginning of react-script you would do this to populate the passed along variables into the environment.
const passAlong = JSON.parse(process.env.PASSALONG);
Object.assign(process.env,passAlong);
Method 2 - what I would do
Using the spawn method would involve just setting process.env how you like in file1.js and then adding something like this at the end of file1.js
// somewhere along the way
process.env.FOO = 'bar';
process.env.OAUTH = 'easy-crack';
process.env.N = 'eat';
// at the end of the script
require('child_process').spawnSync(
'node', // Calling a node script is really calling node
[ // with the script path as the first argument
'/path/to/react-script', // Using relative path will be relative
'start' // to where you call this from
],
{ stdio: 'inherit' }
);
so what I want to do is sending an string which is a path for my image .. I want to do that in routes file . because I receive in it the image path like that
const imageReko = require("./image-Reko");
if(req.body.act === "post") {
if(req.body.img){
imageReko(req.body.img)
}
const post = new Post({
content: req.body.content,
firstName:req.body.firstName,
lastName: req.body.lastName,
img: req.body.img,
});
so what I have done is export all my image recognition file like that
const imageReko = () =>{
const photo = 'image2.jpg' // i want to put my string that i have passed it from my route files
// somecode
}
I described in comment what I want to do ..
From what I understand you want to get a string from the request body then pass it into a function in ./image-Reko which will store it in a variable.
Function Parameters
First of all the function in `image-Reko` has no parameters. This means when you pass `req.body.img` the function will ignore it since it cannot use it. To fix this you need to add a parameter to the function like so:
const imageRecko = (img) => {
// Code here
}
const vs. var and let
In the function you defined a variable called `photo` with the keyword `const` which declares a constant variable. This variable can not be re declared or redefined so you can change this variable with your function. To fix this:
const imageReko = (img) => {
var photo = img;
}
This way you can assign the variable inside the function.
This is what i understood from your question let me know if i missed something. Good luck with your project!
Since you pass req.body.img as parameter for imageReko() you can use it in the imageReko function
const imageReko = (img) =>{
const photo = img
// somecode
}
I'm facing a problem I'm not able to resolve on my own, maybe some of you faced the same problem.
Let me show you what I'm trying to do, here is the mock:
let mockConfig = {name: 'dude'};
jest.mock('../../../configManager', () => mockConfig);
configManager is a dependency of the function I'm trying to test.
It works well but I want to change the returning object of configManager in another test so the tested function behaves differently.
Let me show you, here is the function I'm testing:
const config = require('../../../configManager');
module.exports = () => {
if (config.name === 'dude') {
do stuff;
}
if (config.name === 'dudette') {
do something else;
}
So, typically, I want to change the config.name to 'dudette' to be able to test the second part of my function.
Naturally, when I want to do this with an imported function, I just do:
let mockJsonQueryResult = { value: 'stuff' };
jest.mock('json-query', () => jest.fn(() => mockJsonQueryResult));
and then in the test, I directly set another value to mockJsonQueryResult:
mockJsonQueryResult = { value: 'hotterStuff' };
But I don't find any way of doing this with a dependency that returns an object, with a dependency returning a function, no problem.
Is there even any way of doing this?
Thanks in advance!
Edit: this is not the same as how to change jest mock function return value in each test? as #Dor Shinar suggested because his problem is to mock a function, even if it is inside a returning object it is still a function, I just want to change a value inside the returned object.
So, I found a solution I'm not completely satisfied with but it works:
I simply set the original full object and then for my tests, change the value of specific properties by setting them directly before calling the function I want to test.
example:
let mockConfig = { person: { name: 'dude', origin: {country: 'France'} } };
jest.mock('../../../configManager', () => mockConfig);
mockConfig.person = {};
mockConfig.person.name = 'dudette';
You don't need to mock the module at all.
If your module export is just an object with property values then just change the properties as needed.
Here is a simple working example to demonstrate:
configManager.js
module.exports = {
name: 'original'
}
code.js
const config = require('./configManager');
module.exports = () => `name: ${config.name}`;
code.test.js
const config = require('./configManager');
const func = require('./code');
test('func', () => {
expect(func()).toBe('name: original'); // Success!
config.name = 'dude';
expect(func()).toBe('name: dude'); // Success!
config.name = 'dudette';
expect(func()).toBe('name: dudette'); // Success!
})
Details
A module binding can't be directly changed to something else:
const config = require('./configManager');
config = { name: 'mock' }; // <= this doesn't work
...but you can change the properties of an object representing a module binding:
const config = require('./configManager');
config.name = 'mock'; // <= this works!
...and any code using the module will automatically see the changes.
I'm using Node v0.10.11 on Ubuntu 12.04. I can't figure out what I'm missing to make streams of URLs work with the request module.
This program is trying to go to a mailing list site, find the download links for each month, then download the pages for each month.
Mikael's readme says "The first argument can be either an url or an options object. The only required option is URI, all others are optional.
uri || url - fully qualified uri or a parsed url object from url.parse()"
If I call url.parse(www.targeturl.com), I get
Error: options.uri is a required argument
If I don't use url.parse, I get
Error: Invalid URI "www.freelists.org/archive/si-list/06-2013"
(this link works perfectly fine in my browsers)
I've cut the code down to 42 lines. Any advice welcome
var request = require('request'),
url = require('url'),
stream = require('stream'),
cheerio = require('cheerio'), // a reduced jQuery style DOM library
Transform = require('stream').Transform
var DomStripStream = function(target) {
this.target = target;
stream.Transform.call(this,{objectMode: true});
}
DomStripStream.prototype = Object.create(
Transform.prototype, {constructor: {value: DomStripStream}}
)
DomStripStream.prototype.write = function () {
this._transform.apply(this, arguments);
};
DomStripStream.prototype.end = function () {
this._transform.apply(this, arguments);
this.emit("end");
};
DomStripStream.prototype._transform = function(chunk, encoding, callback) {
chunk = chunk ? chunk.toString() : "";
$ = cheerio.load(chunk);
domLinks = $(this.target);
$(domLinks).each(function (i, link) {
currLink = 'www.freelists.org' + $(link).attr('href')
// currLink = url.parse(currLink)
request(currLink, function (error, response, body) {
console.log(error);
})
});
}
var fs = require("fs"),
output = fs.createWriteStream("out.txt"),
mainPage = new DomStripStream('td a')
request('http://www.freelists.org/archive/si-list').
pipe(mainPage).
pipe(output);
add http:// or https:// in the url