Categories
JavaScript Answers

How to write a line into a .txt file with Node.js?

To write a line into a .txt file with Node.js, we call the appendFile function.

For instance, we write

const fs = require("fs");

fs.appendFile("log.txt", "new data", (err) => {
  if (err) {
    // append failed
  } else {
    // done
  }
});

to call appendFile to append 'new data' to log.txt.

And we get the error from err if there’re any errors.

Categories
JavaScript Answers

How to fix writeFile no such file or directory error with Node?

To fix writeFile no such file or directory error with Node, we call the mkdirp function to create the directory if it doesn’t exist.

For instance, we write

const mkdirp = require("mkdirp");
const fs = require("fs");

const writeFile = async (path, content) => {
  await mkdirp(path);
  fs.writeFileSync(path, content);
};

to define the writeFile function.

In it, we call mkdirp to create the directory at the path if it doesn’t exist.

Then we call writeFileSync to write the file to the path.

Categories
JavaScript Answers

How to return a complex JSON response with Node.js?

To return a complex JSON response with Node.js, we call the res.json method.

For instance, we write

res.json({ msgId: msg.fileName });

to call res.json to return the object as the response body.

Categories
JavaScript Answers

How to update all clients using Socket.io and Node?

To update all clients using Socket.io and Node, we call the emit method.

For instance, we run

io.sockets.emit("users_count", clients);

to call emit to emit the users_count event with the clients object as the payload.

Categories
JavaScript Answers

How to run Node.js on port 80?

To run Node.js on port 80, we route port 80 to the local port the Node app is running on.

For instance, we run

sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

to run iptables to add a route entry to route port 80 to our Node app running on port 8080.