Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active December 8, 2018 12:52
Show Gist options
  • Save ivankisyov/6ea482f930bd763f093140ee6912d6e7 to your computer and use it in GitHub Desktop.
Save ivankisyov/6ea482f930bd763f093140ee6912d6e7 to your computer and use it in GitHub Desktop.
Node.js

Node.js

Set environment variables

on windows

set PORT=4000

dotenv => https://github.com/motdotla/dotenv

further reading on env vars and dotenv: https://dev.to/deammer/loading-environment-variables-in-js-apps-1p7p

Using environment variables

const port = process.env.PORT || 3000;

Write to a file

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

async function getUsers() {
  let { data: users } = await axios.get(
    "https://jsonplaceholder.typicode.com/users"
  );

  users = JSON.stringify(users);

  fs.writeFile("./test.txt", users, function(err) {
    if (err) {
      return console.log(err);
    }

    console.log("The file was saved!");
  });
}

getUsers();

Get the project's root path

const path = require("path");

module.exports = path.dirname(process.mainModule.filename);

Serve files statically

// the public dir will be readable by the client
app.use(express.static(path.join(__dirname, "public")));

Send html files

router.get("/add-product", (req, res, next) => {
  res.sendFile(path.join(rootDir, "views", "add-product.html"));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment