Categories
JavaScript Answers

How to share sessions with Socket.IO 1.x and Express 4.x?

Sometimes, we want to share sessions with Socket.IO 1.x and Express 4.x.

In this article, we’ll look at how to share sessions with Socket.IO 1.x and Express 4.x.

How to share sessions with Socket.IO 1.x and Express 4.x?

To share sessions with Socket.IO 1.x and Express 4.x, we can use the express-session package.

For instance, we write

const express = require("express");
const Server = require("http").Server;
const session = require("express-session");
const RedisStore = require("connect-redis")(session);

const app = express();
const server = Server(app);
const sio = require("socket.io")(server);

const sessionMiddleware = session({
  store: new RedisStore({}),
  secret: "keyboard cat",
});

sio.use((socket, next) => {
  sessionMiddleware(socket.request, socket.request.res || {}, next);
});

app.use(sessionMiddleware);

app.get("/", (req, res) => {
  console.log(req.session)
});

sio.sockets.on("connection", (socket) => {
  console.log(socket.request.session)
});


server.listen(8080);

to call session to create the sessionMiddleware.

Then we call sio.use with a callback that calls session with the socket.io request and response objects and the next function` to call the next middleware.

Next, we call app.use with sessionMiddleware to use the session middleware.

Now the Express middlewares that come after app.use(sessionMiddleware) should have the session data available in req.session.

And socket.request.session has the value of the session in the sio.sockets.on handler since sio.sockets.on is called after app.use(sessionMiddleware)

Conclusion

To share sessions with Socket.IO 1.x and Express 4.x, we can use the express-session package.

Categories
JavaScript Answers

How to change the timeout on a Jasmine Node async spec?

Sometimes, we want to change the timeout on a Jasmine Node async spec.

In this article, we’ll look at how to change the timeout on a Jasmine Node async spec.

How to change the timeout on a Jasmine Node async spec?

To change the timeout on a Jasmine Node async spec, we can set the jasmine.DEFAULT_TIMEOUT_INTERVAL value.

For instance, we write

describe("long asynchronous specs", () => {
  let originalTimeout;

  beforeEach(() => {
    originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
  });

  it("takes a long time", (done) => {
    setTimeout(() => {
      done();
    }, 9000);
  });

  afterEach(() => {
    jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
  });
});

to set the jasmine.DEFAULT_TIMEOUT_INTERVAL value to 10000 milliseconds in the beforeEach callback to change the default timeout for each test.

Then we call it with a callback to add a test that calls done after 9000 milliseconds.

And then set jasmine.DEFAULT_TIMEOUT_INTERVAL to originalTimeout in the afterEach callback to reset the timeout to originalTimeout.

Conclusion

To change the timeout on a Jasmine Node async spec, we can set the jasmine.DEFAULT_TIMEOUT_INTERVAL value.

Categories
JavaScript Answers

How to find the size of the file in Node.js?

Sometimes, we want to find the size of the file in Node.js.

In this article, we’ll look at how to find the size of the file in Node.js.

How to find the size of the file in Node.js?

To find the size of the file in Node.js, we can use the fs.statSync method.

For instance, we write

const fs = require("fs");
const stats = fs.statSync("myfile.txt")
const fileSizeInBytes = stats.size;
const fileSizeInMegabytes = fileSizeInBytes / (1024 ** 2);

to call fs.statSync with the path of the file that we want to get the size of.

Then we get the file size in bytes with stats.size.

Next, we convert the size to megabytes with fileSizeInBytes / (1024 ** 2).

Conclusion

To find the size of the file in Node.js, we can use the fs.statSync method.

Categories
JavaScript Answers

How to invoke an AWS Lambda function from within another lambda function with Node.js?

Sometimes, we want to invoke an AWS Lambda function from within another lambda function with Node.js.

In this article, we’ll look at how to invoke an AWS Lambda function from within another lambda function with Node.js.

How to invoke an AWS Lambda function from within another lambda function with Node.js?

To invoke an AWS Lambda function from within another lambda function with Node.js, we can call the lambda.invoke method.

For instance, we write

const AWS = require('aws-sdk');
AWS.config.region = 'eu-west-1';
const lambda = new AWS.Lambda();

exports.handler = (event, context) => {
  const params = {
    FunctionName: 'LambdaB',
    InvocationType: 'RequestResponse',
    LogType: 'Tail',
    Payload: '{ "name" : "Jane" }'
  };

  lambda.invoke(params, (err, data) => {
    if (err) {
      context.fail(err);
    } else {
      context.succeed('Lambda_B said ' + data.Payload);
    }
  })
}

in the first lambda to define a unction that calls lambda.invoke with the params object.

In params, we specify the name of the Lambda function to run with FunctionName.

And we set the Payload that we pass to 'LambdaB'.

Then in LambdaB, we listen for invocations with

exports.handler = (event, context) => {
  context.succeed(event.name);
};

And get the Payload value from event.

Conclusion

To invoke an AWS Lambda function from within another lambda function with Node.js, we can call the lambda.invoke method.

Categories
JavaScript Answers

How to prevent SQL injection in Node.js?

Sometimes, we want to prevent SQL injection in Node.js.

In this article, we’ll look at how to prevent SQL injection in Node.js.

How to prevent SQL injection in Node.js?

To prevent SQL injection in Node.js, we should be using parameterized queries.

For instance, we write

const userId = 5;

const query = connection.query('SELECT * FROM users WHERE id = ?', [userId], (err, results) => {
  //...
});

to call the connection.query method from the node-mysql-native package.

We call it with a parameterized select statement.

We have id = ? and pass in an array with the array of values to replace each ? in the SQL string to escape the values we pass in to replace the ?.

Therefore, userId is escaped before it’s interpolated and the query is run.

Then from the results parameter of the callback, we get the query result.

Conclusion

To prevent SQL injection in Node.js, we should be using parameterized queries.