Categories
Node.js Tips

Node.js Tips — Send Message, Adding End of Line, and S3 Uploads

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Send a Message to a Particular Client with Socket.io

We can send a message to a particular client with socket.io by using the emit method.

For instance, we can write:

io.to(socket.id).emit("event", data);

We call the io.to method with the ID of the client we want to send our message to.

Responding with a JSON object in Node.js

We can use the res.json method with Express to return JSON response.

For instance, we can write:

res.json({ foo: 'bar' });

to return the JSON object that we passed in.

Check if Node.js is Installed or Not

We can check if Node is installed by using the node -v command to display the Node version.

Select and Update Document by _id with node-mongodb-native

To select and update a document by its _id , we can use the mongo.ObjectID constructor to create the ID object.

For instance, we can write:

const mongo = require('mongodb');
const id = new mongo.ObjectID(theId);
collection.update({ '_id': id });

theId is the string of the ID.

Then we use that as the value of the '_id' property.

How to Append to New Line in Node.js

We can append a new line to a file in a Node app by using the open and write methods.

To add the new line, we use the os.EOL property to add the new line character.

This way, the new line will be inserted correctly with all platforms.

For instance, we can write:

const os = require("os");

const addNewLine = (text) => {
  fs.open('/path/to/file', 'a', 666, (e, id) => {
    fs.write(id, `${text}${os.EOL}`, null, 'utf8', () => {
      fs.close(id, () => {
       console.log('file is updated');
      });
    });
  });
}

We created the addNewLine method to open the file.

We open it with append permission as indicated by 'a' .

666 is the file permission which includes a read and writes.

Then we get the file ID in the callback so we can use it to update the file.

In the fs.write call, id is the file ID. The 2nd argument is text content.

os.EOL is the platform-agnostic new line constant.

'utf8' is the UTF-8 encoding.

Then callback is called when writing is done.

Then we clean up the filehandle with fs.close .

Uploading base64 Encoded Image to Amazon S3 via Node.js

To upload a base64 image with S3, we can convert it to the buffer.

Then we can call putObject to upload the file.

For instance, we can write:

const AWS = require('aws-sdk');
AWS.config.loadFromPath('./config.json');
const s3Bucket = new AWS.S3( { params: { Bucket: 'someBucket'} } );

const buffer = new Buffer(req.body.imageBinary.replace(/^data:image/w+;base64,/, ""),'base64');

const data = {
  Key: 123,
  Body: buffer,
  ContentEncoding: 'base64',
  ContentType: 'image/jpeg'
};

s3Bucket.putObject(data, (err, data) => {
  if (err) {
    console.log(err, data);
  } else {
    console.log('success');
  }
});

We firs get the credentials from the config.json file to authenticate for the AWS SDK.

Then we create a buffer from the base64 string.

We’ve to take out the data:image/w+;base64 part.

Then we create a data object with the Key , Body , ContentEncoding and ContentType properties.

Key is the path to the file.

Body has the content of the file.

ContentEncoding has the encoding.

ContentType has the data type.

Then we call putObject to upload the file.

config.json has:

{
  "accessKeyId":"xxxxxxxxxxxxxxxx",
  "secretAccessKey":"xxxxxxxxxxxxxx",
  "region":"us-east-1"
}

Stdout Buffer Issue Using Node child_process’s exec — maxBuffer Exceeded

If we get the ‘maxBuffer exceeded’ error, we can use set the maxBuffer option on exec to increase the buffer size.

For instance, we can write:

exec('ls', { maxBuffer: 1024 ** 2 }, (error, stdout, stderr) => {
  console.log(error, stdout);
});

We set the maxBuffer size in the object in the 2nd argument.

Conclusion

We can use the io.to method to send the message to a given client.

To send JSON response, we can use res.json .

We can update with ID.

To max buffer size of exec can be increased.

We use the os.EOL constant to add a platform-agnostic end of line character.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *