Created
November 6, 2021 14:58
-
-
Save joaobispo2077/cdfd0e6e1246ddddf48034113fa38c74 to your computer and use it in GitHub Desktop.
Setup json server with dynamic actual machine ip address from node js cli using native packages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable import-helpers/order-imports */ | |
/* eslint-disable @typescript-eslint/no-var-requires */ | |
/* prerequisites: | |
- in the root of the project create the file in ./scripts/setupJsonServer.js | |
- json-server installed in the project or globally. | |
*/ | |
// to excute run "node .setupJsonServer.js" | |
// in package.json add following key value script: "dev:server": "node ./scripts/setupJsonServer.js" | |
const util = require('util'); | |
const os = require('os'); | |
const dns = require('dns'); | |
const child_process = require('child_process'); | |
const exec = util.promisify(child_process.exec); | |
const lookup = util.promisify(dns.lookup); | |
const path = require('path'); | |
const PORT = '3333'; | |
const DELAY = '700'; | |
async function setupJsonServer() { | |
try { | |
console.log('Checking if JSON server is already running...'); | |
const { stdout: stdoutCheckJsonServer } = await exec('netstat -aon'); | |
const lines = stdoutCheckJsonServer.split(os.EOL); | |
const jsonServerPort = lines.find((line) => line.includes('json-server')); | |
if (jsonServerPort) { | |
console.log('JSON server is already running.'); | |
return; | |
} | |
console.log('JSON server is not running.'); | |
console.log('Setting up JSON server...'); | |
const hostname = os.hostname(); | |
const ip = await lookup(hostname); | |
console.log(`Setting up json server on ${ip.address}`); | |
await exec('dir'); | |
const root = path.resolve(__dirname, '..'); | |
console.log(`entry into path: ${root}`); | |
await exec(`cd ${root}`); | |
const command = `yarn json-server --host ${ip.address} ./src/services/server.json -p ${PORT} --delay ${DELAY}`; | |
console.log('Running command:', command); | |
console.log('Waiting for json server to start...'); | |
console.log(`Access json server at http://${ip.address}:${PORT}...`); | |
await exec(command); | |
} catch (error) { | |
console.log('error... aborting setup'); | |
console.log(error.message); | |
console.error(error); | |
} | |
} | |
setupJsonServer(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment