Categories
JavaScript Answers

How to fix Karma/Jasmine times out without running tests with Node?

To fix Karma/Jasmine times out without running tests with Node, we increase the timeout for running tests.

For instance, in karma.conf.js, we write

module.exports = function (config) {
  config.set({
    //...
    captureTimeout: 60000,
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 1,
    browserNoActivityTimeout: 60000,
  });
};

to set browserNoActivityTimeout to 60000ms to increase the test timeout.

Categories
JavaScript Answers

How to split and modify a string in Node?

To split and modify a string in Node, we call the split and map methods.

For instance, we write

const str = "123, 124, 234,252";
const arr = str.split(",").map((val) => Number(val) + 1);
console.log(arr);

to call split to split the str string by the commas into a string array.

And then we call map to map each value to their new value by converting them to a number and add 1 to it.

Categories
JavaScript Answers

How to buffer entire file in memory with Node.js?

To buffer entire file in memory with Node.js, we call readFile.

For instance, we write

const fs = require("fs");

fs.readFile("/etc/passwd", (err, data) => {
  // ...
});

to call readFile to open the /etc/passwd file.

And we get the open file data from data.

Categories
JavaScript Answers

How to use FormData in Node.js without browser?

To use FormData in Node.js without browser, we use the URLSearchParams constructor.

For instance, we write

const fs = require("fs");

const form = new URLSearchParams();
form.append("my_field", "my value");
form.append("my_buffer", new Buffer(10));
form.append("my_file", fs.createReadStream("/foo/bar.jpg"));

to create a URLSearchParams object.

Then we call append with the key and value of each form data entry to add it.

We can add buffers and read streams for binary data.

Categories
JavaScript Answers

How to fix JSON.parse(fs.readFileSync()) returning a buffer with Node?

To fix JSON.parse(fs.readFileSync()) returning a buffer with Node, we specify the encoding.

For instance, we write

const squadJSON = JSON.parse(fs.readFileSync("file.json", "utf8"));

to call readFileSync to open the file.json file.

We specify the encoding is 'utf8' to return a Unicode string instead of a buffer.