Categories
JavaScript Answers

How to download and unzip a zip file in memory in Node?

To download and unzip a zip file in memory in Node, we use the adm-zip module.

To install it, we run

npm install adm-zip

Then we write

const fileUrl =
  "https://github.com/mihaifm/linq/releases/download/3.1.1/linq.js-3.1.1.zip";

const AdmZip = require("adm-zip");
const request = require("request");

request.get({ url: fileUrl, encoding: null }, (err, res, body) => {
  const zip = new AdmZip(body);
  const zipEntries = zip.getEntries();
  console.log(zipEntries.length);

  zipEntries.forEach((entry) => {
    if (entry.entryName.match(/readme/i)) console.log(zip.readAsText(entry));
  });
});

to call request.get with an object with the url of the file to unzip.

We get the zip file’s content from body.

And then we call getEntries to get the items in the zip file.

Categories
JavaScript Answers

How to stream files in Node Express to client?

To stream files in Node Express to client, we create a read stream and pipe it.

For instance, we write

app.use((req, res, next) => {
  if (req.url === "somethingorAnother") {
    res.setHeader("content-type", "some/type");
    fs.createReadStream("./toSomeFile").pipe(res);
  } else {
    next();
  }
});

to call createReadStream to create a read stream to read toSomeFile.

And we call pipe with res to pipe the read stream as the response.

Categories
JavaScript Answers

How to fix Module not found: Can’t resolve ‘fs’ in Next.js application with JavaScript?

To fix Module not found: Can’t resolve ‘fs’ in Next.js application with JavaScript, we set the fs option to false.

For instance, we write

module.exports = {
  webpack5: true,
  webpack: (config) => {
    config.resolve.fallback = { fs: false };

    return config;
  },
};

in webpack.config.js to set fs to false to disable the use of the fs module in the browser environment.

Categories
JavaScript Answers

How to pass variable to html template in Nodemailer?

To pass variable to html template in Nodemailer, we put them in the context property.

For instance, we write

const mailOptions = {
  from: "abc@gmail.com",
  to: "username@gmail.com",
  subject: "Sending email",
  template: "yourTemplate",
  context: {
    username,
    whatever: variable,
  },
};

const info = await transporter.sendMail(mailOptions);

to call sendMail with mailOptions to send the email message.

We set the context property to an object with the template variables to interpolate them in the template.

Categories
JavaScript Answers

How to remove a key with Node redis?

To remove a key with Node redis, we call the del method.

For instance, we write

redis.del('SampleKey');

to remove the entry with key 'SampleKey‘ from Redis with del.