Categories
Node.js Tips

Node.js Tips — Ending Tasks, Express Responses, and Streams

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Stop All Instances of Node.js Server

In Windows, we can stop the Node server by running the taskkill command:

taskkill /im node.exe

We can also add the /f flag to force termination of all Node tasks:

taskkill /f /im node.exe

We can also find the process by the port by using netstat :

netstat -ano | find "LISTENING" | find "8888"

Then we can kill a task by the process ID with the /pid flag:

taskkill /pid 12345

Where 12345 is the process ID from netstat .

We can also use /f to force the task to end.

On Linux, we can write:

killall node

to end all Node tasks.

We can find the task with the given port by running:

netstat -nlp | grep :1234

Then we will find the process ID of the task running on port 1234.

Then we can kill the task with the process ID:

kill 2345

where 2345 is the task ID.

We can also use the -9 flag to force the termination of the task:

kill -9 2345

Fix ‘Origin is not allowed by Access-Control-Allow-Origin’ Error

To fix the ‘origin is not allowed’ error, we can add the Access-Control-Allow-Origin response header.

For instance, if we’re using the http module to create the server, we can write:

var http = require('http');

http.createServer((request, response) => {
  response.writeHead(200, {
    'Content-Type': 'text/plain',
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
  });
  response.end('Hello Worldn');
}).listen(3000);

We call writeHead to write the response headers.

We have:

'Access-Control-Allow-Origin' : '*'

to allow requests from all origins.

And:

'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'

allows all request methods to be invoked.

If we’re using Express, we can create a middleware:

const cors = (req, res, next) => {
  res.header('Access-Control-Allow-Origin', "*");
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
}

Then we can use it by writing:

app.use(cors);

to use the middleware.

It sets the same response headers and calls next to call the next middleware.

Create Streams from a String in Node.Js

We can create a stream with the stream module.

For instance, we can write:

const { Readable } = require('stream');

async function * generate() {
  yield 'hello';
  yield 'world';
}

const readable = Readable.from(generate());

readable.on('data', (chunk) => {
  console.log(chunk);
});

We import the stream module.

Then we create a generator with the data that we want to send to the stream.

Then we use the Readable.from method to create the read stream.

Finally, we listen to the data event with the on method.

chunk has the data piped to the stream.

Access the Request Body When POSTing Using Express

We can access the request body with Express using the body-parser package.

For instance, we can write:

const bodyParser = require('body-parser');
app.use(bodyParser);

Then we can access the request body with req.body .

So we can write:

app.post('/', (req, res) => {
  console.dir(req.body);
  res.send("hello");
});

app.listen(3000);

to get the request body.

Together, we write:

const bodyParser = require('body-parser');
app.use(bodyParser);

app.post('/', (req, res) => {
  console.dir(req.body);
  res.send("hello");
});

app.listen(3000);

Fix ‘TypeError: Router.use() requires middleware function but got a Object’ Error

We use the express.Router method to create a router object where we can add routes.

Then we can export it or and then use it or use it directly.

For instance, we can write:

const tagsRouter = express.Router();

`tagsRouter`.get('/tags', (req, res) => {
  res.json(tags.get());
});

app.use('/tags', `tagsRouter`);

Or we can write:

tags.route.js

const tagsRouter = express.Router();

`tagsRouter`.get('/tags', (req, res) => {
  res.json(tags.get());
});

module.exports = tagsRouter;

app.js

const tagsRouter = require('./`tags.route`');
app.use('/tags', `tagsRouter`);

With the router object, we can group routes.

Conclusion

We can use Express router to group routes.

Also, we can use body-parser to parse the request body.

We can end tasks in various ways.

Read streams can be created easily.

To allow cross-origin communication, we can add some headers to the response.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *