Node js создать html

Node js создать html

Create the content of an html file with one function call.

npm install --save create-html 
  • title
  • script
  • scriptAsync
  • css
  • cssAsync
  • lang
  • dir
  • head
  • body
  • favicon

Simple example that create an html file with the title example :

var html = createHTML(
title: 'example'
>)

Example using all options:

var html = createHTML(
title: 'example',
script: 'example.js',
scriptAsync: true,
css: 'example.css',
lang: 'en',
dir: 'rtl',
head: ' ',
body: '

example

'
,
favicon: 'favicon.png'
>)

Create a file with the html contents using the fs module:

var fs = require('fs')
var createHTML = require('create-html')
var html = createHTML(
title: 'example'
>)
fs.writeFile('index.html', html, function (err)
if (err) console.log(err)
>)

Create a stream by pairing this module with from2-string :

var fromString = require('from2-string')
var createHTML = require('create-html')
var html = createHTML(
title: 'example'
>)
var stream = fromString(html)
stream.pipe(process.stdout)

Pipe content into the html that this module generates by using from2-string and hyperstream

var fs = require('fs')
var fromString = require('from2-string')
var hyperstream = require('hyperstream')
var createHTML = require('./index')
var html = createHTML(
title: 'example'
>)
var hs = hyperstream(
'body': fs.createReadStream('some.html')
>)
var stream = fromString(html)
stream.pipe(hs).pipe(process.stdout)

Multiple CSS and Javascript Files

Multiple script and stylesheets can be added by sending an array instead of a string:

var html = createHTML(
css: ['sheet1.css', 'sheet2.css'],
script: ['script1.js', 'script2.js']
>)

This module comes with a simple command-line tool for creating html files.

Install it globally with npm i -g create-html

Usage: create-html [options] Options: --title, -t Page title --script, -s JavaScript filename, optional --script-async, -a Add async attribute to script tag --css, -c CSS filename, optional --favicon, -f Site favicon --lang, -l Language of content --dir, -d Direction of content --head, -H Content to insert into tag --body, -b Content to insert into tag --output, -o File name. optional. default: stdout --help, -h Show this help message 
create-html --title "an example html file" 

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Generate HTML with node.js

License

Hargne/html-creator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

const htmlCreator = require("html-creator"); const html = new htmlCreator([  type: "head", content: [  type: "title", content: "Generated HTML", >,  type: "style", content: ` #cool-text  color: red; > `, >, ], >,  type: "body", content: [  type: "div", content: [  type: "div", content: "This is a cool text 😎", attributes:  id: "cool-text" >, >,  type: "a", content: "Click here", attributes:  href: "/path-to-infinity", target: "_blank" >, >, ], >, ], >, ]); const result = html.renderHTML();

The above code will result with the following HTML output:

> html> head> title>Generated HTMLtitle> style> #cool-text < color: red; > style> head> body> div> div id pl-s">cool-text">This is a cool text 😎div> a href pl-s">/path-to-infinity" target pl-s">_blank">Click herea> div> body> html>

Visit the wiki for more examples of usage, method reference and further reading.

Do you believe that something is missing from this plugin or perhaps is not working as intended? Awesome-pants! Help is always appreciated. Just be sure to read through the Contributing Handbook (and remember to have a jolly good time).

About

Generate HTML with node.js

Источник

Render HTML In Node.js

render html with nodejs

Let’s see how to create a server and render some HTML in Node.js. First up, we will create a new file named server.js in our project root. We are writing our first server in Node.js! It might seem odd if you’re coming from a PHP background to talk about creating our first server in a JavaScript file, but that is in fact what we are about to do. This is because we are used to having a server like Nginx or Apache which are set up to interpret PHP code. The Nginx or Apache process then serves the HTML files to the user. In this case we are writing our own server. Let’s see how to complete this task.

Creating A Web Server In Node.js

node server js

Node.js provides the ability to create server functionality and bypass the traditional idea of a stand alone web server. For example in Node.js, we can specify a port to communicate on, which domain to use, and now to handle http requests. This new file will have instructions to listen to http requests, and do something with these requests.

This server.js file is the file that Node.js will execute, and will set up a type of loop. Node will continue to listen to requests as long as we allow the program to run. Let’s add a bit of code to our file.

server.js

let http = require('http'); let handleRequest = (request, response) => < response.writeHead(200, < 'Content-Type': 'text/plain' >); response.write('Hi There!'); response.end(); >; http.createServer(handleRequest).listen(8000);

So what does this file do? Well, we can see that we use require() like we’ve learned about before to make use of the http module in this file. Once the http module is imported, we have access to the createServer() method. Believe it or not, that one method creates an entire web server for you! Notice that we also chain on the listen() method which specifies which port to listen for http requests on. Now, we see that createServer() is actually accepting an argument of handleRequest . This is required because it is in this function that we set up the logic to handle any http requests the server gets. We created this function ourselves, and then pass in a reference to that function.

So what is this handleRequest() function doing? Well we can see that it accepts a request and a response as two arguments. These arguments are automatically passed in to this function by Node.js. So in this function, we are not really going to do anything with the request, but we do need to set up what the server will do with a response. We first use the writeHead() method to set the header of the response. The first argument to that function is the status code we would like to send. A 200 means everything went well. The next argument that gets passed is a JavaScript object which specifies the content type we are sending back. After that we call the write() function, so that we can just render some text to the screen. Lastly, we call the end() method to indicate that we are done handling the request and the response can be sent to the user who made the http request.

Let’s try it out, we can run our program by typing node server.js at the command line and notice that it looks like the program is just hanging. Well, it is basically running in a loop so that it can respond any time a request comes in.

node server in the browser

Now, we can load up http://localhost:8000/ in the browser and see what happens.

Cool! We just set up a fully functioning web server in Node.js in about 10 lines of code! Here are the important methods we used.

Serving HTML Files With Node.js

index html file

Now that we have a server up and running, let’s see how to render html with Node.js. To do this, we of course need an html file to serve so we can create and populate an index.html file now.

So in the section above, we simply sent some text to the browser in response to an incoming http request. Now, we no longer want to send just simple text, but rather an actual html file. How can we do this? The index.html file is currently on our server. We would need to somehow grab the file and attach it to a response, and then send that response back to the user who made the http request. Therefore we need a way to use the file system to get the file, and then send it to the user.

Fetching The HTML File on our File System

In the snippet below, the first addition we will make to our server.js script is to require the file system module in Node.js. You’re likely a pro at that by now! Then in the original response.writeHead() method, notice that we change the content type from ‘text/plain’ to ‘text/html’. This changes the header that gets sent to the browser and informs the browser that it is now dealing with an actual html file and to parse it as such. Once that is in place, we use the file system module to make a call to fs.readFile() and we read in the index.html file that lives on our server. We specify the file we want to read in with the first argument. We don’t need the second argument in this case so we set it to null, but we do need the third argument which is a callback function. This function is executed once Node.js has finished reading in the index.html file. In other words, it is a way to tell Node.js what to do next so to speak.

Attaching the file to the response and sending it to the browser

What we use this callback function for is to check to make sure there are no errors, but if there is an error – we will send back a 404 not found message to the browser. However, if the operation is successful, we are going to send a response back to the browser and we are attaching the file to that response by passing it as an argument. This data is our actual index.html file. Finally, we make a call to response.end().

let http = require('http'); let fs = require('fs'); let handleRequest = (request, response) => < response.writeHead(200, < 'Content-Type': 'text/html' >); fs.readFile('./index.html', null, function (error, data) < if (error) < response.writeHead(404); respone.write('Whoops! File not found!'); >else < response.write(data); >response.end(); >); >; http.createServer(handleRequest).listen(8000);

In the meantime, make sure your server is running with nodemon by typing nodemon server.js at the command prompt. We can see how the server automatically restarts as we edit and update our JavaScript code.

c:node>nodemon server.js [nodemon] 1.17.4 [nodemon] to restart at any time, enter `rs` [nodemon] watching: *.* [nodemon] starting `node server.js` [nodemon] restarting due to changes. [nodemon] starting `node server.js` [nodemon] restarting due to changes. [nodemon] starting `node server.js` [nodemon] restarting due to changes. [nodemon] starting `node server.js`

index-html file rendered in google chrome

Loading up the browser at http://localhost:8000/ shows us that now, we are getting a glorious html rendering of our index.html file!

Just for grins, let’s see what happens if we had not changed the content type.

let http = require('http'); let fs = require('fs'); let handleRequest = (request, response) => < response.writeHead(200, < 'Content-Type': 'text/plain' >); fs.readFile('./index.html', null, function (error, data) < if (error) < response.writeHead(404); respone.write('file not found'); >else < response.write(data); >response.end(); >); >; http.createServer(handleRequest).listen(8000);

send html as plain text

Loading the page now gives us a very different result. Now we see how important it is to set the response header correctly!

Render HTML In Node.js Summary

In this tutorial, we saw how to output html files to the browser with Node.js. It was pretty cool to see how we were able to create our own web server with just a very minimal amount of JavaScript code. We also saw how to read in a file from the file system, attach it to a response, and send it back to the user. Of course we’ll be looking at how to vastly simplify all of this using some of the Popular Node.js Frameworks soon, but for now it’s great to see how to make things happen using raw JavaScript and the Node.js runtime only.

Источник

Читайте также:  How to check if deque is empty python
Оцените статью