NodeJS – All about

Basic

Update node engine

brew update
brew upgrade node

How to run shell command and get output?

Non-stream formatted output

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function lsWithGrep() {
  try {
      const { stdout, stderr } = await exec('ls | grep js');
      console.log('stdout:', stdout);
      console.log('stderr:', stderr);
  } catch (err) {
     console.error(err);
  };
};

lsWithGrep();

Output stream

const { execSync } = require('child_process');
// stderr is sent to stdout of parent process
// you can set options.stdio if you want it to go elsewhere
const stdout = execSync('ls');
const { spawnSync} = require('child_process');

const child = spawnSync('ls', );
console.error('error', child.error);
console.log('stdout ', child.stdout);
console.error('stderr ', child.stderr);

Reference how-to-run-shell-script-file-or-command-using-nodejs

How to write API requests?

GraphQL & Axios

const axios = require("axios")
axios({
    url: 'https://1jzxrj179.lp.gql.zone/graphql',
    method: 'post',
    data: {
        query: `
            query PostsForAuthor {
                author(id: 1) {
                    firstName
                    posts {
                        title
                        votes
                    }
                 }
            }`
    }
}).then((result) => {
    console.log(result.data)
});

Fetch

const fetch = require('node-fetch');
fetch('https://1jzxrj179.lp.gql.zone/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: '{ posts { title } }' }),
})
.then(res => res.json())
.then(res => console.log(res.data));


// Pass variables for dynamic arguments
fetch({
query: `query PostsForAuthor($id: Int!) {
author(id: $id) {
firstName
posts {
title
votes
}
}
}`,
variables: { id: 1 },
}).then(res => {
console.log(res.data);
});

Apollo fetch

const { createApolloFetch } = require('apollo-fetch');
const fetch = createApolloFetch({
    uri: 'https://1jzxrj179.lp.gql.zone/graphql',
});

fetch({
    query: '{ posts { title }}',
}).then(res => {
    console.log(res.data);
});

package.json

How to run npm scripts

Run multiple commands in parallel

"scripts": {
    "start-test": "cordova prepare && cordova platform add browser",
}

$ yarn start-test

Run multiple commands in parallel ignoring error of previous command

"scripts": {
    "start-test": "cordova prepare; cordova platform add browser",
}

$ yarn start-test

Be the first to comment

Leave a Reply

Your email address will not be published.


*