Categories
JavaScript Answers

How to set Node.js global proxy setting?

To set Node.js global proxy setting, we use the global-tunnel-ng package.

For instance, we write

const globalTunnel = require("global-tunnel-ng");

globalTunnel.initialize({
  host: "10.0.0.10",
  port: 8080,
  proxyAuth: "userId:password",
  sockets: 50,
});

to call initialize with an object with the proxy options and credentials to connect to the proxy.

Categories
JavaScript Answers

How to read and output jpg image with Node?

To read and output jpg image with Node, we read it with readFile.

For instance, we write

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

fs.readFile("image.jpg", (err, data) => {
  if (err) {
    throw err;
  }
  http
    .createServer((req, res) => {
      res.writeHead(200, { "Content-Type": "image/jpeg" });
      res.end(data);
    })
    .listen(8080);
});

to call readFile to read the image.jpg file.

And then we call createServer with a callback that calls res.end with the read data to return that as the response.

We call writeHead to write the Content-Type header with the MIME type as its value.

Categories
JavaScript Answers

How to fix ISODate is not defined with Node?

To fix ISODate is not defined with Node, we use the Date constructor.

For instance, we write

const d = new Date(dateString);

to create a date from dateString with the Date constructor.

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.