Node.js writing parse data to a variable [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I'm writng a node.js app to read messages from Serial Port. Reading data and logging it into console works fine, althought I'm wondering how to save data value from Serial Port to a variable. I want to pass it further to a MySQL, so I need the data to be stored in variable.
I tried to use global variable, but it keeps saying "undefined". I also tried to pass the value using return in js function, but it doesn't work too. Here's my code:
var SerialPort = require('serialport');
const parsers = SerialPort.parsers;
const parser = new parsers.Readline({
delimiter: '\r\n'
});
var port = new SerialPort('COM10',{
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
port.pipe(parser);
parser.on('data', function(data) {
console.log('Received data from port: ' + data);
});
Please tell me how to store data from parser.on in a variable.

Doesn't variable = data;work?

Related

How to retrieve query parameters from GET request using javascript? [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 12 months ago.
Below is my GET request. I am trying to retrieve the client_id and redirect_uri parameters.
https://sdkapp.example.com:8443/central-login/index.html?client_id=dtvClient&redirect_uri=https://www.example3.com:443/callback
And then utilize those values, in a embedded js script within the same html page.
Config.set({
clientId: //fetched query parameter for client_id
redirectUri: // fetched query parameter for redirect_uri
});
If this is on the client you can use URL and searchParams
// const url = new URL(location.href); // uncomment and delete next line
const url = new URL("https://sdkapp.example.com:8443/central-login/index.html?client_id=dtvClient&redirect_uri=https://www.example3.com:443/callback"); // for example
const obj = {
"clientId": url.searchParams.get("client_id"),
"redirectUri": url.searchParams.get("redirect_uri")
};
console.log(obj)
// Config.set(obj)
If on the server: for example node also has URL
And here is an answer for php: Get URL query string parameters

Fetch Query Parameters [duplicate]

This question already has an answer here:
How do I parse a URL for a specific Query Paramter in javascript?
(1 answer)
Closed 2 years ago.
I need to fetch authorization code from the URL . It is present as a query string parameters.
When I run the belowo URL
https://XXX.authenticaion.com/oauth/authorize?response_type=code&client_id=sb!t113
It redirects to
http://localhost:8080/?code=8wFgU1GJo3
I need to parse the localhost URL and fetch the code.
Please help on how to retrieve the code
Code :
const url = 'https://XXX.authenticaion.com/oauth/authorize?response_type=code&client_id=sb!t113'
const config = {
method: "GET"
};
const response = await fetch(url ,config);
console.log('Response Text...............'+response.text())
You could use plain js URL web api to create URL object and then get the code value.
const url = 'http://localhost:8080/?code=8wFgU1GJo3'
const code = new URL(url).searchParams.getAll('code')
console.log(code)

express can`t get query param from url [duplicate]

This question already has answers here:
How to get GET (query string) variables in Express.js on Node.js?
(26 answers)
Closed 4 years ago.
I use express framework and react on front app for manage http request on node app. A have method :
app.get('/api/matches', async (req, res) => {
console.log(req.originalUrl); // /api/matches/
console.log(req.query); // {}
...
when I use url like http://localhost:3000/matches?id=123 I expect to get id inside req.query object but instead I get empty {} object. Also I tried to check how express see url using originUrl object, its return without query ?id=123.
You need to use your URL like http://localhost:3000/api/matches/?id=123. Notice that api word. This is because your GET route has /api/matches and request will look for path /api/matches. Doing that change will work for you. Then with that change you will be able to get req.query as {id: 123}

Global Variable not updating from request get function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I would like to set a global variable and set it value from inside of node.js request module get function. Here is my code -
var req = require('request');
var server = '';
req.get('http://httpbin.org/headers',function(err,res,body){
server = res.headers.server;
console.log(body);
});
console.log(server); // result undefined
Problem is everytime I get undefined.
It's not recommended you set global in a callback.
It's better you use events for this
EDIT
app.on('serverHeader', function(data){
//do stuff
});
app.get('...', function(req, res, cb){
app.emit('serverHeader', res.headers);
});

Something I don't understand about node.js callbacks [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
So, I'm trying to send an email confirmation token to an user, and for that, I'm trying to use the crypto module to generate the token. I have this:
var transport = this.NewTransport(), // This generates a nodemailer transport
token;
// Generates the token
require('crypto').randomBytes(48, function(ex, buf) {
token = buf.toString('hex');
});
// Uses nodemailer to send the message, with the token.
var message = {
from: 'test#email.com',
to: 'receiver#email.com',
subject: 'Token',
text: token,
html: token
};
transport.sendMail(message, function(err){
if(err) return res.send({s: 0});
return res.send({s: 1});
});
Well, the token generated by the crypto module isn't getting assigned to the token variable, I assume this is because of the asynchronous nature of the randomBytes function.
How can I actually... save the token somewhere so I can send it through the email? Or do I have to include ALL of the email-sending code inside of the randomBytes callback function? Is this the way it has to be done in node? Is there any other way, so that the token gets generated in time, and actually sent?
Sorry, I'm quite new to node and I'm still confused about callbacks sometimes. Thanks.
You should really wrap your code within functions. It makes it easier to manage callbacks and simultaneously maintain the code. Have a look at how I reworked what you provided... Keep in mind I haven't checked the code so there may be a few bugs.
var crypto = require('crypto'),
transport = this.NewTransport(); // This generates a nodemailer transport
generateToken(sendMail);
function generateToken(callback) {
// Generates the token
var token;
crypto.randomBytes(48, function(ex, buf) {
token = buf.toString('hex');
if (typeof callback === 'function') {
callback(token);
}
});
}
function sendMail(token) {
// Uses nodemailer to send the message, with the token.
var message = {
from: 'test#email.com',
to: 'receiver#email.com',
subject: 'Token',
text: token,
html: token
};
transport.sendMail(message, function(err){
if(err) return res.send({s: 0});
return res.send({s: 1});
});
}

Categories

Resources