Categories
JavaScript Answers

How to change working directory in my current shell context when running Node.js script?

To change working directory in my current shell context when running Node.js script, we call the process.chdir method.

For instance, we write

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

to call the process.chdir method to go up one directory level.

Categories
JavaScript Answers

How to pass arguments to require (when loading module) with Node.js?

To pass arguments to require (when loading module) with Node.js, we export a function.

For instance, we write

class MyClass {
  constructor(arg1, arg2, arg3) {}
  myFunction1() {}
  myFunction2() {}
  myFunction3() {}
}

module.exports = (arg1, arg2, arg3) => {
  return new MyClass(arg1, arg2, arg3);
}

in myClass.js to export a function that returns the MyClass instance.

Then we write

const MyClass = require("/myClass.js")(arg1, arg2, arg3);

in app.js to import myClass.js and call its constructor with the arguments.

Categories
JavaScript Answers

How to fix npm ERR! Refusing to delete / code EEXIST error with JavaScript?

To fix npm ERR! Refusing to delete / code EEXIST error with JavaScript, we delete the node_modules and reinstall all the packages.

After deleting the node_modules folder, we reinstall all the packages with

npm install
Categories
JavaScript Answers

How to connect to TCP Socket from browser using JavaScript?

To connect to TCP Socket from browser using JavaScript, we call the socket.create method.

For instance, we write

chrome.experimental.socket.create("tcp", "127.0.0.1", 8080, (socketInfo) => {
  chrome.experimental.socket.connect(socketInfo.socketId, (result) => {
    chrome.experimental.socket.write(socketInfo.socketId, "Hello, world!");
  });
});

to call the socket.create method to create a socket to 127.0.0.1 port 8080.

We then call socket.connect method to connect to the socket with the socketInfo.

And then we call write to send data to the socket.

Categories
JavaScript Answers

How to change the cache path for npm (or completely disable the cache) on Windows?

To change the cache path for npm (or completely disable the cache) on Windows, we run the config set cache command.

For instance, we run

> npm config set cache C:\dev\nodejs\npm-cache --global 

to set the cache directory to the C:\dev\nodejs\npm-cache folder.

We then run

npm --global cache verify

to verify the cache directory is set.