Categories
Node.js Tips

Node.js Tips — Non-Module Libraries, Blobs, setTimeout, and More

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

setTimeout and Node.js

setTimeout waits for a minimum number of milliseconds before running.

It’s not a guarantee.

Passing 0, non-number of a negative number will cause it to wait a minimum number of milliseconds in Node.

For example, if we have:

setTimeout(() => {
  console.log('hello');
}, 100)

Then we wait for 100ms at least before running the callback.

Node.js Project Naming Conventions for Files and Folders

A typical Node project has the /bin folder for scripts, helpers, and binaries.

/lib for the app.

/config for the configuration.

/public for the public files.

And /test for the tests.

Including JavaScript Class Definition from Another File in Node.js

We can export the class and import it in another file.

For instance, we can write:

person.js

class Person {
  //...
}

module.exports = Person;

Then in another file, we write:

app.js

const Person = require('./person');
const person = new Person();

We use require to require the person module and then instantiate the class that we imported.

Also, we can do the same with ES modules.

For instance, we can write:

person.js

export default class Person {}

app.js

import Person from './person';
const person = new Person();

We import the person module and use it the same way.

The export has to be a default export so that we can import the class without braces.

Change Working Directory in the Current Shell Context when Running Node Script

To change the working directory in a Node script, we can use the process.chdir method.

For instance, we can write:

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

to move one directory up.

Load Vanilla Javascript Libraries into Node.js

If we want to load JavaScript libraries that aren’t modules, we can use the vm module.

For instance, we can write:

const vm = require("vm");
const fs = require("fs");
module.exports = (path, context) => {
  context = context || {};
  const data = fs.readFileSync(path);
  vm.runInNewContext(data, context, path);
  return context;
}

We read in the script file with the function we’re exporting and run it with vm.runInNewContext .

data has the script file. path is the file path.

context is the context that the script is running in, which is the global object.

Then we can use execfile to run the file:

const execfile = require("execfile");
const context = execfile("example.js", { globalVar: 42 });
console.log(context.foo());
context.globalVar = 100;

example.js is a file with:

function foo() {
  return 'bar';
}

We should get 'bar' from the console log since foo is a global function.

globalVar is a global variable.

ES6 Variable Import Name in Node.js

We can import with import by name by writing:

const import = async () => {
  try {
    const module = await import('./path/module');
  }  catch (error) {
    console.error('import failed');
  }
}

We use the import function which returns a promise.

It can be used to import ES modules by the path string we passed in.

If it’s successful, it’ll resolve to the module.

Convert Blob to File in JavaScript

We can convert a blob to a file in JavaScript in a few ways.

We can pass in the blob to the File constructor.

For instance, we can write:

const file = new File([blob], "name");

where the blob is the blob instance and 'name' is the file name.

We can pass in more arguments:

const file = new File([blob], "name", { lastModified: 1534584790000 });

We set the lastModfiied date with the timestamp in the 3rd argument.

We can also set the lastModifiedDate property of the blob.

For instance, we can write:

const blobToFile = (blob, fileName) => {
  blob.lastModifiedDate = new Date();
  blob.name = fileName;
  return blob;
}

We set the lastModifiedDate on the blob , which is a Blob instance to set the last modified date,

blob.name sets the file name.

Conclusion

We set the modified date of a blob or file in various ways.

setTimeout doesn’t guarantee the delay time.

We can export classes with modules.

It takes some effort to load non-module JavaScript libraries in Node apps.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *