Categories
JavaScript Answers

How to download file stream and writeFile with Node.js axios?

To download file stream and writeFile with Node.js axios, we set the responseType.

For instance, we write

const response = await axios({
  method: "get",
  url: "https://example.com/my.pdf",
  responseType: "stream",
});
response.data.pipe(fs.createWriteStream("/temp/my.pdf"));

to call axios to make a get request.

We set the responseType to 'stream' to download the data as a stream.

And then we call response.data.file with a write stream to pipe the read stream we get from response to the write stream to write the response data to the my.pdf file.

Categories
JavaScript Answers

How to parse XLSX with Node and create JSON?

To parse XLSX with Node and create JSON, we use the xlsx module.

For instance, we write

const XLSX = require("xlsx");
const workbook = XLSX.readFile("master.xlsx");
const sheetNameLlist = workbook.SheetNames;
console.log(XLSX.utils.sheet_to_json(workbook.Sheets[sheetNameLlist[0]]));

to call readFile to read master.xlsx.

And we get the sheets names from SheetNames.

Next, we call sheet_to_json with the sheet we get from workbook.Sheets[sheetNameLlist[0]] to return the sheet data as JSON.

Categories
JavaScript Answers

How to load file with Node?

To load file with Node, we call the readFile method.

For instance, we write

const fs = require("fs");

fs.readFile(__dirname + "/test.txt", (err, data) => {
  if (err) {
    throw err;
  }
  console.log(data.toString());
});

to call readFile with path of the file to read from.

And we get the file data from data in the callback.

Categories
JavaScript Answers

How to log Node Express JavaScript to a output file?

To log Node Express JavaScript to a output file, we use the express.logger method.

For instance, we write

const logFile = fs.createWriteStream("./myLogFile.log", { flags: "a" });

app.use(express.logger({ stream: logFile }));

to create the logFile write stream with createWriteStream.

We call createWriteStream with the log file path and an object with flag set to 'a' for append.

Then we call express.logger to with an object with stream set to logFile to return a middleware that we use in our app to add logging to the file.

Categories
JavaScript Answers

How to create or update with Node Sequelize?

To create or update with Node Sequelize, we use the upsert method.

For instance, we write

User.upsert({ a: "a", b: "b", username: "john" });

to call upsert with an object with the value to create or update.

It’ll look for the item to update by the primary key.