Categories
JavaScript Answers

How to set up two different static directories in Node.js Express framework?

To set up two different static directories in Node.js Express framework, we call express.static.

For instance, we write

app.use("/public", express.static(__dirname + "/public"));
app.use("/public2", express.static(__dirname + "/public2"));

to call express.static to return 2 middlewares toi server the /public and /public2 folders as static directories.

And then we call app.use to use the middlewares to make the folders available via the /public and /public2 URLs.

Categories
JavaScript Answers

How to perform a full text search in MongoDB and Mongoose and JavaScript?

To perform a full text search in MongoDB and Mongoose and JavaScript, we set the $text.$search property.

For instance, we write

const schema = new Schema({
  name: String,
  email: String,
  profile: {
    something: String,
    somethingElse: String,
  },
});
schema.index({ name: "text", "profile.something": "text" })

to create the schema schema.

And we add an index to it by calling `schema.index with the fields we want to index.

We add 'text' indexes to the name and profile.something fields.

Then we do a fuzzy search with

MyModel.find({ $text: { $search: searchString } })
  .skip(20)
  .limit(10)
  .exec((err, docs) => {
    //...
  });

to call find with the $text.$search property set to the query we want to run.

And we get the results returned from docs.

Categories
JavaScript Answers

How to fix bcrypt invalid elf header error when running Node app?

To fix bcrypt invalid elf header error when running Node app, we should use a bcrypt version that’s compatible with the OS the app is running.

To do this, we run

npm install bcrypt

to install bcrypt on the current operating system so that it’s built to run on the current OS.

Categories
JavaScript Answers

How to fix env: node: No such file or directory error in Mac?

To fix env: node: No such file or directory error in Mac, we reinstall Node and npm.

For instance, we run

$ brew uninstall --force node
$ brew uninstall --force npm

to uninstall node and npm with brew.

And then we reinstall both with

$ brew install node
Categories
JavaScript Answers

How to use JavaScript async/await with streams?

To use JavaScript async/await with streams, we use the util.promisify method.

For instance, we write

const fs = require("fs");
const crypto = require("crypto");
const util = require("util");
const stream = require("stream");

const pipeline = util.promisify(stream.pipeline);

const hash = crypto.createHash("sha1");
hash.setEncoding("hex");

const run = async () => {
  await pipeline(fs.createReadStream("/some/file/name.txt"), hash);
  console.log("Pipeline succeeded");
};

run();

to call util.promisify with stream.pipeline to return the promisified pipeline function.

And then we call pipeline with a read stream created from createReadStream to run the pipeline.