Categories
JavaScript Answers

How to write an array to file with Node.js?

Sometimes, we want to write an array to file with Node.js.

In this article, we’ll look at how to write an array to file with Node.js.

How to write an array to file with Node.js?

To write an array to file with Node.js, we can create a write stream.

For instance, we write

const fs = require('fs');

const file = fs.createWriteStream('array.txt');

file.on('error', (err) => {
  /* error handling */
});

arr.forEach((v) => {
  file.write(v.join(', ') + '\n');
});

file.end();

to call fs.createWriteStream with the path of the file to write to.

Then we call arr.forEach to loop through the array and call file.write to write to the stringified version of the array to the the stream.

And once, we’re done, we call file.end to close the stream.

Conclusion

To write an array to file with Node.js, we can create a write stream.

Categories
JavaScript Answers

How to add unit tests for Node.js and Socket.io?

Sometimes, we want to add unit tests for Node.js and Socket.io.

In this article, we’ll look at how to add unit tests for Node.js and Socket.io.

How to add unit tests for Node.js and Socket.io?

To add unit tests for Node.js and Socket.io, we can set up our socket.io connection before each test, and clear the connection after each test.

For instance, we write

const io = require('socket.io-client')
const assert = require('assert')
const expect = require('expect.js');

describe('Suite of unit tests', () => {
  let socket;

  beforeEach((done) => {
    socket = io.connect('http://localhost:3001', {
      'reconnection delay': 0,
      'reopen delay': 0,
      'force new connection': true
    });
    socket.on('connect', () => {
      console.log('worked...');
      done();
    });
    socket.on('disconnect', () => {
      console.log('disconnected...');
    })
  });

  afterEach((done) => {
    if (socket.connected) {
      console.log('disconnecting...');
      socket.disconnect();
    } else {
      console.log('no connection to break...');
    }
    done();
  });

  describe('First test', () => {

    it('Doing some things with indexOf()', (done) => {
      expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
      expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
      done();
    });

    it('Doing something else with indexOf()', (done) => {
      expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
      expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
      done();
    });

  });

});

to call io.connect in the beforeEach callback to connect to our socket.io server before each test.

The we call done in the 'connect' event callback to run our test.

Likewise, we in the afterEach callback, we call socket.disconnect to disconnect from our socket.io server after each test is socket.connected is true.

Then in our tests, we run some test code and then call done when we’re done.

Conclusion

To add unit tests for Node.js and Socket.io, we can set up our socket.io connection before each test, and clear the connection after each test.

Categories
JavaScript Answers

How to make synchronous requests in Node.js?

Sometimes, we want to make synchronous requests in Node.js.

In this article, we’ll look at how to make synchronous requests in Node.js.

How to make synchronous requests in Node.js?

To make synchronous requests in Node.js, we can use the sync-request module.

To install it, we run

npm i sync-request

Then we use it by writing

const request = require('sync-request')

try {
  const res1 = request('GET', url1);
  const res2 = request('GET', url2);
} catch (e) {}

to call request with 'GET' to make GET requests to url1 and url2.

Conclusion

To make synchronous requests in Node.js, we can use the sync-request module.

Categories
JavaScript Answers

How to check in Node if module exists and if exists to load?

Sometimes, we want to check in Node if module exists and if exists to load.

In this article, we’ll look at how to check in Node if module exists and if exists to load.

How to check in Node if module exists and if exists to load?

To check in Node if module exists and if exists to load, we can wrap our require call with a try-catch block.

For instance, we write

try {
  const m = require('/foo/bar');
  //  ...
} catch (ex) {
  handleErr(ex);
}

to wrap our require call with a try block.

If the module doesn’t exist, then an error will be thrown, and so we can catch the error with the catch block.

Conclusion

To check in Node if module exists and if exists to load, we can wrap our require call with a try-catch block.

Categories
JavaScript Answers

How to log the response body with Express?

Sometimes, we want to log the response body with Express.

In this article, we’ll look at how to log the response body with Express.

How to log the response body with Express?

To log the response body with Express, we can create our own middleware to intercept the response and log it.

For instance, we write

const logResponseBody = (req, res, next) => {
  const oldWrite = res.write
  const oldEnd = res.end;

  const chunks = [];

  res.write = (chunk, ...args) => {
    chunks.push(chunk);
    return oldWrite.apply(res, [chunk, ...args]);
  };

  res.end = (chunk, ...args) => {
    if (chunk) {
      chunks.push(chunk);
    }
    const body = Buffer.concat(chunks).toString('utf8');
    console.log(req.path, body);
    return oldEnd.apply(res, [chunk, ...args]);
  };

  next();
}

app.use(logResponseBody);

to create the logResponseBody middleware function that sets res.write to a function that calls chunks.push to push the response chunks to the chunks array.

And then we return the result of the original res.write write method, which is stored in oldWrite.

Likewise, we set res.end to a method that combine the chunks into a buffer with Buffer.concat.

And then we log the body with console.log.

And then we call oldEnd.apply and return the results.

Finally, we call next to call the next middleware.

Conclusion

To log the response body with Express, we can create our own middleware to intercept the response and log it.