Showing posts with label Node JS. Show all posts
Showing posts with label Node JS. Show all posts

Monday, 12 June 2017

node mssql preparestatment output identity id

I'm using https://www.npmjs.com/package/mssql

I'm using sql.PreparedStatement to do the insert and I would like to use the request.output('id', sql.Int) to get my identity id(auto increasing ID). But I'm getting null value.

query:

INSERT INTO queue (refid, name, channel) VALUES (@refid, @name, @channel)

If I use request.output('refid', sql.Int) it was able to get the refid.

If I use OUTPUT INSERTED.id the id will store in recordset as below:

<
  recordsets[[object]],
  recordset[<id:xx>],
  output<refid:123>,
  rowsAdected: [1],
  returnValue: 0
>

What I prefer is:

<
  recordsets[[object]],
  recordset[],
  output<id:999, refid:123>,
  rowsAdected: [1],
  returnValue: 0
>



via hendry91

NodeJS - Crytography (S.S.E.)

Someone can help me to do the inverted operation of this? http://www.paranoiaworks.mobi/sse/file_encryption_specifications.html

I have encrypted a file on Android with an app that uses this specification (the algorithm was AES-256). I want to decrypt the file using node-js, the crypto module only is not sufficient, because there is not the necessary functions to derive the key like the app did. There is some library that I can use to do that?

PS: I need to decrypt it using node-js and not using their app for desktop because it's a very sensible file and I need to work with it only on memory.

Thanks in advance.



via Murillo Brandão

Implement helmet-csp on individual routes

I'm creating a sample Express app to demonstrate Content-Security-Policy (CSP) headers and am trying to use helmet-csp.

All of the documentation for helmet-csp shows it used as standard third-party-middleware via app.use(csp({ ... })) - this adds the CSP headers to every route in my application, but I want to customize it on individual routes.

Sample App

var express = require('express');
var http = require('http');
var csp = require('helmet-csp');
var app = express();

app.use(csp({
    directives: {
        frameSrc: ["'none'"]
    }
}));

app.get('/', (request, response) => {
    response.send('hi, :wave: =]');
});

app.get('/frameable', (request, response) => {
    response.send('you can frame me!');
});

http.createServer(app).listen(80, (err) => {
    if (err) {
        return console.log('error', err);
    }
});

With the above, every route receives the CSP header:

Content-Security-Policy: frame-src 'none'

In the /frameable route, I would want to override this CSP header to be:

Content-Security-Policy: frame-src 'self'

Whenever I need/want to customize a header set by helmet-csp on a per-route basis, do I need to manually override them inside each app.get with a line such as:

response.setHeader('Content-Security-Policy', "frame-src 'self'");

Or is there a way to do this via helmet-csp itself?



via newfurniturey

Within Express, how can I add core modules to my package.json dependencies so I can require them in my js files?

I'm trying to use the core module 'connect' and, if I understand the situation correctly, express uses that module internally. I want to require it manually, and I've tried to insert it into my dependencies within my package.json file. Maybe I'm not installing it correctly with my git bash? I'm taking shots in the dark here, but here are my dependencies within the file.

"dependencies": {
"connect": "2.4.2",
"accepts": "~1.3.3",
"array-flatten": "1.1.1",
"content-disposition": "0.5.2",
"content-type": "~1.0.2",
"cookie": "0.3.1",
"cookie-signature": "1.0.6",
"debug": "2.6.7",
"depd": "~1.1.0",
"encodeurl": "~1.0.1",
"escape-html": "~1.0.3",
"etag": "~1.8.0",
"finalhandler": "~1.0.3",
"fresh": "0.5.0",
"merge-descriptors": "1.0.1",
"methods": "~1.1.2",
"on-finished": "~2.3.0",
"parseurl": "~1.3.1",
"path-to-regexp": "0.1.7",
"proxy-addr": "~1.1.4",
"qs": "6.4.0",
"range-parser": "~1.2.0",
"send": "0.15.3",
"serve-static": "1.12.3",
"setprototypeof": "1.0.3",
"statuses": "~1.3.1",
"type-is": "~1.6.15",
"utils-merge": "1.0.0",
"vary": "~1.1.1"

}



via Forrest Carlton

gulp-replace from template and project source and merge into single file

Alright, one for the ages. The issue is I am trying to merge the structure from multiple sources into a single one. One of my sources is from the template.html which contains the base structure for index.html -source-. I trying to find a solution that replaces html block data from the source -index.html- body tag into the destination -template.html- lastly create a new merged document which outputs to -dest-.

File structure that is as follows:

  • public
  • ---assets
  • ------template.html
  • ---src
  • ------app.js
  • ------index.html
  • ------main.css
  • ---dist
  • ------merged.html

I am using npm package gulp-replace (but open to other packages).

var gulp = require('gulp');
var htmlreplace = require('gulp-html-replace');
var copycat = require('gulp-copycat');

gulp.task('default', function() {
    // create a watch task
    gulp.task('default', function() {
        gulp.src('assets/template.html')
            .pipe(htmlreplace({
                'cssInline': {
                    src: gulp.src('sheetgmail/main.css'),
                    tpl: '<style>%s</style>'
                },
                'body': gulp.src('sheetgmail/index.html'),
                'headscript': {
                    src: null,
                    tpl: '%s'
                },
                'js': {
                    src: gulp.src('sheetgmail/app.js'),
                    tpl: "<script type='text/javascript'>%s</script>"
                },
            }, {
                keepUnassigned: false,
                keepBlockTags: true,
                resolvePaths: false
            }))
            .pipe(gulp.dest('dist/'));
    });
});



via Isaiah Monroe Davis

couldn't node-gyp rebuild (ERROR binding.cc : No such)

I'm trying node-gyp rebuild but get fatal error.

c1xx : fatal error C1083: Cannot open source file: '..\src\binding.cc': No 
such
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` 
fail
gyp ERR! stack     at ChildProcess.onExit 
(C:\Users\Admin\AppData\Roaming\npm\no
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit 
(internal/child_proces
gyp ERR! System Windows_NT 10.0.15063
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" 
"C:\\Users\\Admin\\AppDat
gyp ERR! cwd C:\Users\Admin
gyp ERR! node -v v6.11.0
gyp ERR! node-gyp -v v4.0.0
gyp ERR! not ok

I use Python 2.7 node-gyp -v v4.0.0 node -v v6.11.0

and node-gyp configure will warn with missing input binding.cc.



via L.seonbeen

Wordpress API with Express

Is it possible to make an external http get request from Wordpress API using express?

Let's say I want to make a get request to http://demo.wp-api.org/wp-json/wp/v2/posts - This are a list of posts from wordpress.

Sample:

router.get('/posts', function(req, res){
     I should make an external http request here from wordpress api
     ("http://demo.wp-api.org/wp-json/wp/v2/posts")

     Then I want to display the response as json
}



via Sherwin Ablaña Dapito

One of the problems with using Expo development when the React native

When I was in the use of Expo development project, the first execution NPM run ios will be submitted to the errors, and then execute once is normal.

Excuse me, what's the solution?

As shown in figure:

Error screenshot

Error is as follows: › npm run ios

react-native-starterkit@0.1.0 ios /Users/****/work/react-native-starterkit

react-native-scripts ios

10:09:56: Starting packager...

10:10:09: Starting simulator...

10:10:30: Failed to start simulator:

Error: Process exited with non-zero code: 60

Exiting...



via 祝梓毅

How to enable print media emulation in headless Chrome?

Is there a way to enable simulated device mode or emulated print media mode in headless Chrome in Linux?

It can be done manually in DevTools like so:

Enable print media emulation

The goal is to take a full-page screenshot in emulated print media mode without injecting or modifying any CSS. I'm already able take screenshots of web pages via Node.js, but not in emulated print media mode. I've searched, but am also unable to find a helpful CLI switch.

Example:StackOverflow print emulation

How to do this programmatically via CLI or Node.js? Is it even possible?



via Drakes

Node.js - How to return after all asynchronous calls have finished

As shown bellow, I am pushing the object link_to_json returns into an array allShirts declared in html_to_json.

However, the console.dir on the third last line and the return value of html_to_json logs an array of undefined references. Which I presume is because console.dir and return is executed before link_to_json functions finished.

How do I ensure the return value of html_to_json is a filled up allShirts array?

//Go to individual links and scrape relevant info
const link_to_json = (link) => {
    request(link, (err, res, body) => {
        if (!error_handler(err, res, link)) {
            const $ = cheerio.load(body);
            const shirt_detail = $('.shirt-details').find('h1').text();

            const Title = shirt_detail.substr(shirt_detail.indexOf(' ') + 1);
            const Price = shirt_detail.substr(0, shirt_detail.indexOf(' '));
            const ImageURL = $('.shirt-picture').find('img').attr('src');
            const URL = link;

            return new Shirt(Title, Price, ImageURL, URL);
        } else return {};
    });
}

//Crawl through all individual links listed in Root
const html_to_json = body => {
    const allShirts = [];
    const $ = cheerio.load(body);

    $('.products').find('a').each((index, val) => {
        allShirts.push(link_to_json(rootURL + $(val).attr('href')));
    });

    console.dir(allShirts); // <--- HERE
    return allShirts;
}



via Ja. L

Having an issue with nodemailer and postfix

I'm receiving this error when I try to run nodemailer

{ Error: 139776600639296:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:794:
code: 'ECONNECTION', command: 'CONN' }

as shown in this snippet

'use strict';
const nodemailer = require('nodemailer');

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
    host: 'smtp.localhost',
    port: 465,
    secure: true, // secure:true for port 465, secure:false for port 587
});

// setup email data with unicode symbols
let mailOptions = {
    from: '"Fred Foo 👻" <foo@blurdybloop.com>', // sender address
    to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers
    subject: 'Hello ✔', // Subject line
    text: 'Hello world ?', // plain text body
    html: '<b>Hello world ?</b>' // html body
};

// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message %s sent: %s', info.messageId, info.response);
});

I cannot figure out here I'm going wrong with this. I left off the auth info on purpose as it said it would assume it had been authenticated already. Any help would be greatly appreciated - I've been scratching my head at this for days. Thanks!



via Zach Hill

Automatically Emit watchPosition() with socket.io without JS Interval

I'm looking for a way to listen in for when watchPosition() gets a new gps coordinate and then emit this automatically without using a javascript interval to blindly keep emiiting the values of watchPosition() with or without a change in the device's location.

Basically, update the latitude and longitude only when the device's location changes.

Thanks in advance!



via William Ebuka Okafor

node.js not printing to console

I am trying to use sockets in my api. However I could not see the logs in the console.

The only output I see is:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
We are live on8000

Here is my server.js file:

// server.js
const express        = require('express');
const MongoClient    = require('mongodb').MongoClient;
const bodyParser     = require('body-parser');
const app            = express();
const port           = 8000;

var server = require('http').createServer(app);
var io = require('socket.io')(server);

const db = require('./config/db');

app.use(express.static(__dirname + '/../app'));
app.use(bodyParser.urlencoded({ extended: true }));


MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err);

    //check below line changed
     require('./app/routes')(app, database);
    app.listen(port,() => {
        console.log("We are live on"+port);
    });

    app.get('/', function(req, res){
      res.sendFile(__dirname + '/index.html');
    });


    io.on('connection',function(socket){
      console.log('client connected');

      socket.on('disconnect', function () {
        console.log('disconnect');
      });

    });

})

and the index.html is:

<!DOCTYPE html>
<html>
  <head><title>Hello world</title></head>
  <script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
</script>
  <body>Hello world</body>
</html>

I see Hello world on the web browser, but I could not see 'client connected' on the console log.



via Teja Nandamuri

keep string between two words node js express

I have a string like:

var str = saGDJGJDJGlgk abc_start asjdgjgjgdfjakgfja abc_end csjhgfhsgfgfugvgjdj abc_start djkhfjwhjfgwjgkfvvg abc_end.

I'm displaying this string in my browser using:

res.send('/page/+result);

I want to filter out result such that only the content which starts at abc_start and end at abc_end remains. How do I do that in node.js?

For eg: output: abc_start asjdgjgjgdfjakgfja abc_end abc_start djkhfjwhjfgwjgkfvvg abc_end

I tried using : str.split('abc_start').pop().split('abc_end').shift();

But I'm not gettting desired output.Please help.



via user8151624

How do you pass a filename to the next action in a Gulp pipeline using gulp-tap?

I have a Gulp task which takes an HTML file and inlines styles taken from a CSS file using gulp-inline-css. The original version of my task used the same CSS file for each HTML file. Now I would like to have the task choose a CSS file based on the filename of the HTML file it is processing.

I am using gulp-tap to get the filename. The inliner() function takes the path to the CSS file and runs all the inlining stuff.

The following Gulp task runs inliner() for each of the files, but it seems to be failing to inject the results back into the stream. I've tried a few different approaches, but I can't seem to get the results of inliner() back into the original stream.

gulp.task('inline', inline);

function inline() {
  return gulp.src('dist/**/*.html')
    .pipe(tap( (file, t) => {
      let fileName = path.basename(file.path);
      let cssPath = getStylesheetPathFromHtmlPath(fileName);
      return inliner(cssPath);
    }))
    .pipe(gulp.dest('dist'));
}

function inliner(cssPath) {
  var css = fs.readFileSync(cssPath).toString();
  var mqCss = siphon(css);
  var pipe = lazypipe()
    .pipe(inlineCss, {
      applyStyleTags: false,
      removeStyleTags: true,
      preserveMediaQueries: true,
      removeLinkTags: false
    })
    .pipe(replace, '<!-- <style> -->', `<style>${mqCss}</style>`)
    .pipe(replace, `<link rel="stylesheet" type="text/css" href="css/${getStylesheetNamespace(cssPath)}.css">`, '')
    .pipe($.htmlmin, {
      collapseWhitespace: true,
      minifyCSS: true
    });
  console.log(cssPath)
  return pipe();
}

Am I using gulp-tap incorrectly? This seems like a very simple use case.



via oatmealsnap

Ajax header causing 400 response when tested on node/Heroku, but works on localhost

This all works fine offline, but when I upload it to Heroku I keep getting 400 errors, and it never reaches any of the routes. It does get to the routes when I comment out the header. What's going on here? Any guesses?

I'm basically trying to send a JWT token when the page is loaded to see if the user needs to login again, or if I can just retrieve their info. Works fine tested on localhost with node.

        $.ajax({
            url: 'users/preauth',
            type: 'POST', 
            dataType: 'json',
            // contentType: "application/json ;charset=UTF-8",
            headers: {"Authorization": TOKEN},
        }).done( function(result){ 
        }).fail(function(err){ 
        })

Is it a CORS issue? And if it is, how do I set it up with my Express app to allow the authorization header?

Is there a security risk intrinsic to allowing headers, and if so, is there a better way to send the token without an authorization header?



via Luddens Desir

Creating Javascript Regex from C

Is it possible to create a RegExp javascript object, using C/C++? I'm just curious about it.

Example:

const myCLib = require('myCLib');
myCLib("/\\s/", "g"); => return regex object /\g/g

Thank you.



via Celo

How to access results of shopify-node-api request outside callback function

I'm building a Shopify app and I'm running into an issue while using the shopify-node-api module. This is the code I'm working with:

collectProducts: ['storedProducts', function(results, callback) {

  const collected_products = results.storedProducts;

  for (var i = 0; i < collected_products.length; i++) {

    Shopify.post('/admin/collects.json', {
      "collect": {
        "product_id": collected_products[i].product_id,
        "collection_id": process.env.DAILY_COLLECTION
      }
    }, function(err, data, headers){
      collected_products[i].collect_id = data.collect.id;
    });
  }

  callback(null, collected_products);
}],

For clarity's sake, the collectProducts item is part of an async function. I'm trying to gather the collect ID from the response to the post request and update the collect_id value in collected_products. The issue is I can't seem to access the collected_products array from inside the callback function for the post request. Is there a way to 1. simply return that value for each iteration of the for loop or 2. access the collected_products array from within that callback function to store those values?

Thanks in advance for any answers!



via paperbeatsscissors

run user defined function, if number of user connected through sockets is atleast one - Nodejs

I am trying to find a way to stop setInterval(test,5000) function from running if no user is connected to the socket stop setInterval function as it causes lot of waste of resources.

I found the method but I dont know how to put it

io.engine.clientsCount  //this will tell number of users connected but only inside socket.on function.

below is my code:

var connectCounter = 0;  


app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});


 function test()
  {
    httpk.get("api-url", function(res) {
        var body = ''; 
        res.on('data', function(data){
            body += data;
        });

        res.on('end', function() {
            var parsed = JSON.parse(body);
            console.log(parsed.johndoe.example1);
            nsp.emit('live-quote', parseFloat(parsed.johndoe.example1);
        });
    });
  }

     setInterval(test,5000);

nsp.on('connection', function(socket){


  //Make a http call
  connectCounter++;
  nsp.emit('live-users',connectCounter);
  console.log('1 user connected, Total Joined: '+connectCounter);

  socket.on('disconnect', function(){
    connectCounter--;
    nsp.emit('live-users',connectCounter);
    console.log('1 user disconnected, Total Left: '+connectCounter);


  });

console.log("total clients: "+io.engine.clientsCount);

if(io.engine.clientsCount >= 1)
{
  //do something
  //if I put setInterval here it will cause problems, that is for each connection it will run setInterval causing lot of http get request
  // meaning, if 100 users then 100 get request in 5 seconds (depending on setInterval time).
}

});

How do I best stop execution of SetInterval(test,5000) if no users connected?



via Murlidhar Fichadia

Piping HTTP 'CONNECT' requests to another net.Socket and getting the response back

I'm trying to set up a reverse proxy server that takes HTTP(S) requests and relays the requests to an exit node. The exit node will give a response back to the master server and the master proxy should return the result to the client that initiated the request.

Like this:

[CLIENT] ---HTTP(S) REQ---> [MASTER PROXY] --- RELAY REQ ---> [EXIT NODE]
   ^                                                            |
    \--- RELAY RESP --- [MASTER PROXY] <--- HTTP(S) RESP ------/

Insecure HTTP is easy. I'm using Net.Socket.Write for comm between master proxy & exit node.

Secure HTTPS is difficult. I don't want to throw cert errors. For a standard reverse proxy you'd pipe the TCP connection like this:

var http = require('http'),
    net = require('net'),
    httpProxy = require('http-proxy'),
    url = require('url'),
    util = require('util');

var proxy = httpProxy.createServer();

var server = http.createServer(function (req, res) {
  util.puts('Receiving reverse proxy request for:' + req.url);

  proxy.web(req, res, {target: req.url, secure: false});
}).listen(8213);

server.on('connect', function (req, socket) {
  util.puts('Receiving reverse proxy request for:' + req.url);

  var serverUrl = url.parse('https://' + req.url);

  var srvSocket = net.connect(serverUrl.port, serverUrl.hostname, function() {
    socket.write('HTTP/1.1 200 Connection Established\r\n' +
    'Proxy-agent: Node-Proxy\r\n' +
    '\r\n');
    srvSocket.pipe(socket); // pipe the connection to allow handshake directly between server/client
    socket.pipe(srvSocket); // pipe the connection to allow handshake directly between server/client
  });
});

But I can't figure out how to pipe to the exit node and get a valid response in plaintext all the way back to the requesting client. Does anyone have any suggestions on how to achieve this?



via rdbell