Categories
JavaScript Answers

How to write a .nvmrc file which automatically change Node version?

To write a .nvmrc file which automatically change Node version, we put the Node version into the file.

For instance, we we run

$ node -v > .nvmrc

to get the Node.js version with node -v and put it into the .nvmrc file with >.

Categories
JavaScript Answers

How to send file in response with Node.js?

To send file in response with Node.js, we call pipe to pipe a stream.

For instance, we write

const http = require("http");
const fileSystem = require("fs");
const path = require("path");

http
  .createServer((request, response) => {
    const filePath = path.join(__dirname, "myfile.mp3");
    const stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
      "Content-Type": "audio/mpeg",
      "Content-Length": stat.size,
    });

    const readStream = fileSystem.createReadStream(filePath);
    readStream.pipe(response);
  })
  .listen(2000);

to call createServer with a callback that calls createReadStream to read the file at filePath.

Then we call readStream.pipe with response to pipe the file data as the response.

We call writeHead to write the file metadata as the header.

Categories
JavaScript Answers

How to fix npx command not found with JavaScript?

To fix npx command not found with JavaScript, we can install it.

To install it, we run

npm i -g npx

to install npx globally with npm i -g.

Categories
JavaScript Answers

How to upload base64 encoded Image to Amazon S3 via Node.js?

To upload base64 encoded Image to Amazon S3 via Node.js, we call the putObject method.

For instance, we write

const AWS = require("aws-sdk");
AWS.config.loadFromPath("./s3_config.json");
const s3Bucket = new AWS.S3({ params: { Bucket: "myBucket" } });
const buf = Buffer.from(
  req.body.imageBinary.replace(/^data:image\/\w+;base64,/, ""),
  "base64"
);
const data = {
  Key: req.body.userId,
  Body: buf,
  ContentEncoding: "base64",
  ContentType: "image/jpeg",
};
s3Bucket.putObject(data, (err, data) => {
  if (err) {
    console.log(err);
    console.log("Error uploading data: ", data);
  } else {
    console.log("successfully uploaded the image!");
  }
});

to convert the base64 string to a buffer with the Buffer.from method.

We replace the prefix with 'base64' before doing the conversion with replace.

Then we create a data object with Body set to the buf buffer.

Finally, we call putObject to upload the data.

Categories
JavaScript Answers

How to change working directory in my current shell context when running Node.js script?

To change working directory in my current shell context when running Node.js script, we call the process.chdir method.

For instance, we write

const process = require("process");
process.chdir("../");

to call the process.chdir method to go up one directory level.