Categories
JavaScript Answers

How to loop through files in a folder Node.js?

Sometimes, we want to loop through files in a folder Node.js.

In this article, we’ll look at how to loop through files in a folder Node.js.

How to loop through files in a folder Node.js?

To loop through files in a folder Node.js, we can use the fs promises module and the for-of loop.

For instance, we write

const loopFiles = async (dir) => {
  try {
    const files = await fs.promises.readdir(dir);

    for (const file of files) {
      const p = path.join(moveFrom, file);
      const stat = await fs.promises.stat(p);

      if (stat.isFile()) {
        console.log("'%s'  file.", fromPath);
      } else if (stat.isDirectory()) {
        console.log("'%s' directory.", fromPath);
      }
    }
  } catch (e) {
    console.error(e);
  }

}

to define the loop function that gets the contents of dir with readdir.

Then we loop through the files array returned from the promise returned by readdir.

Next, we use the for-of loop to loop through files.

We get the full path p with path.join.

And then we call stat with p to get the data about the file or folder.

Then we call isFile to check if the the entity at p is a file.

And we call isDirectory to check if the the entity at p is a folder.

Conclusion

To loop through files in a folder Node.js, we can use the fs promises module and the for-of loop.

Categories
JavaScript Answers

How to use specific middleware in Express for all paths except a specific one?

Sometimes, we want to use specific middleware in Express for all paths except a specific one.

In this article, we’ll look at how to use specific middleware in Express for all paths except a specific one.

How to use specific middleware in Express for all paths except a specific one?

To use specific middleware in Express for all paths except a specific one, we can use the express-unless package.

To install it, we run

npm i express-unless

Then we can use it by writing

app.use(requiresAuth.unless({
  path: [
    '/index.html',
    {
      url: '/',
      methods: ['GET', 'PUT']
    }
  ]
}))

to only use requireAuth except for the /index.html route. or the GET or PUT / routes.

Conclusion

To use specific middleware in Express for all paths except a specific one, we can use the express-unless package.

Categories
JavaScript Answers

How to host multiple Node.js sites on the same IP or server with different domains?

Sometimes, we want to host multiple Node.js sites on the same IP or server with different domains.

In this article, we’ll look at how to host multiple Node.js sites on the same IP or server with different domains.

How to host multiple Node.js sites on the same IP or server with different domains?

To host multiple Node.js sites on the same IP or server with different domains, we can use the diet package.

To install it, we run

npm i diet

Then we write

const server = require('diet');

const app = server()
app.listen('http://example.com/')
app.get('/', ($) => {
  $.end('hello world ')
})

const sub = server()
sub.listen('http://subdomain.example.com/')
sub.get('/', ($) => {
  $.end('sub domain!')
})

const other = server()
other.listen('http://other.com/')
other.get('/', ($) => {
  $.end('other domain')
})

to call server to create a web server.

And we call listen with the domain of each web server.

Finally, we call get to create a get route with path / on each server.

In the callback of get, we call $.end to send a response.

Conclusion

To host multiple Node.js sites on the same IP or server with different domains, we can use the diet package.

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.