I'm trying to send a string with a newline using Express.
const express = require('express');
const app = express();
persons = [//...];
app.get('/info', (req,res) => {
res.send(`Phonebook has info for ${persons.length} people.
${Date()}`);
});
I've read online that as of ES6, backticks can be used to construct multi-lines but it does not seem to be working.
My desired output is:
Phonebook has info for 4 people.
Thu Oct 10 2019 18:54:01 GMT-0700 (Pacific Daylight Time)
I've also tried the following:
app.get('/info', (req,res) => {
res.send(`Phonebook has info for ${persons.length} people.\n${Date()}`);
});
I've read online that you can also just use '\n' but that also does not work.
What am I doing wrong? I've been following the advice I've found online but I cannot get a new line to appear.
Try using \r\n instead of just \n. \n is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).
"\n" does work. If you do a document.
Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.
Methods to send response from server to client are:Using send() function. Using json() function.
It's a bad practice in node.js to execute such 'complex' tasks in the same process as http server. Consider using background workers, queues or something like that.
Nodejs is very powerful as it allows javaScript to be used as a server-side language, which is achieved by the modules/packages it comes with, such as http which allow it to create an HTTP server. With nodeJS, we can also build GUIs, Mobile applications, Desktop applications, APIs, Command Line Tools, etc.
With nodeJS, we can also build GUIs, Mobile applications, Desktop applications, APIs, Command Line Tools, etc. REST (Representational State Transfer) is an architectural style that defines a set of constraints to be used to create web services. REST API is a way of accessing web services in a single and flexible way without having any processing.
This format is called JSON Lines . Instead of sending: Line-separated data elements can be read, parsed and processed as they are being read from the socket, without waiting for the rest of the elements to be received. This approach is much more memory efficient as only the elements which are processed at a given time are kept in memory.
The solution was to use a <br/>
tag instead of \n since the purpose of my res.send() was to send HTML to my local browser. Thanks to @Jason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With