Categories
JavaScript Answers

How to download source from npm without installing it with JavaScript?

To download source from npm without installing it with JavaScript, we run npm view [package name] dist.tarball.

For instance, we run

wget $(npm view lodash dist.tarball)

to download the source for the lodash package without installing it with npm view and wget.

Categories
JavaScript Answers

How to convert a Buffer into a ReadableStream in Node.js?

To convert a Buffer into a ReadableStream in Node.js, we call the Readable.from method.

For instance, we write

const { Readable } = require("stream");

const stream = Readable.from(myBuffer);

to call Readable.from to convert the myBuffer to a readable stream.

This is avilable from Node.js 10.17.0 and up.

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.