Node js loading html files

Can I load a local html file with the cheerio package in node.js?

I have a few html files on my harddrive that I’d like to use jquery on to extract data from. Is this possible to do using cheerio? I’ve tried giving cheerio the local path but it doesn’t work. One idea I had would be to create a web server in node, read from the html file, and then pipe it to cheerio through the server — would this

3 Answers 3

The input is an html string, so you need to read the html content yourself:

var fs = require('fs'); cheerio.load(fs.readFileSync('path/to/file.html')); 

A html file can be read asynchronously with the readFile function from the fs module. When the reading of the file finished the callback function is passed two arguments (err, data) .

The received data contains the html content and can be simply passed to the cheerio load function.

var cheerio = require('cheerio'); var fs = require('fs'); fs.readFile('path/to/file.html', 'utf8', function(err, data) < if (err) throw err; var $ = cheerio.load(data); console.log($.html()); >); 

Sidenote: Because the encoding utf8 is specified as an optional second argument, the typeof data is a string. If the encoding is ommitted data will be a buffer. The load function understands this nonetheless, because the buffer is internally converted to a string with:

if (Buffer.isBuffer(content)) content = content.toString(); 

Documentation of fs.readFile()

Источник

How to run html file using node js

I am new to node js. I have installed node js server in my system but I am not sure how to run a simple html file using node js?

You can’t «run html file» with node.js. Node.js is a JavaScript environment for developing server-side Web applications. Html files are usually run by web-browsers.

10 Answers 10

You can use built-in nodejs web server.

Add file server.js for example and put following code:

var http = require('http'); var fs = require('fs'); const PORT=8080; fs.readFile('./index.html', function (err, html) < if (err) throw err; http.createServer(function(request, response) < response.writeHeader(200, ); response.write(html); response.end(); >).listen(PORT); >); 

And after start server from console with command node server.js . Your index.html page will be available on URL http://localhost:8080

Читайте также:  Возведение в степень питон функция

I am getting errors like this: 2 ‘require’ was used before it was defined. var http = require(‘http’); 5 Expected an identifier and instead saw ‘const’. const PORT=8080; 5 Stopping. (26% scanned). const PORT=8080;

Just install http-server globally

where ever you need to run a html file run the command http-server For ex: your html file is in /home/project/index.html you can do /home/project/$ http-server

That will give you a link to accessyour webpages: http-server Starting up http-server, serving ./ Available on: http://127.0.0.1:8080 http://192.168.0.106:8080

I don’t think this is a great solution. You should not install npm packages globally when it can be avoided. The whole entire Node infrastructure has moved decidedly away from throwing a -g into everything.

I tried installing installing http-server without -g and node through an error when I tried to start the server. It seems that -g is still required when instaling this particular package.

Installing globally requires sudo so I installed without the -g in my project directory. Then, I ran index.html , which is in the project directory, as node_modules/http-server/bin/http-server .

Actually, I ran into a question—how to daemonize it? In the above method, it would run on a shell. So unless I use screen like app or able to keep my shell open forever, the server would get cut-off at some point.

I too faced such scenario where I had to run a web app in nodejs with index.html being the entry point. Here is what I did:

  • run node init in root of app (this will create a package.json file)
  • install express in root of app : npm install —save express (save will update package.json with express dependency)
  • create a public folder in root of your app and put your entry point file (index.html) and all its dependent files (this is just for simplification, in large application this might not be a good approach).
  • Create a server.js file in root of app where in we will use express module of node which will serve the public folder from its current directory.
  • server.js
var express = require('express'); var app = express(); app.use(express.static(__dirname + '/public')); //__dir and not _dir var port = 8000; // you can use any port app.listen(port); console.log('server on' + port); 

Источник

Render HTML file in Node.js and Express.js framework

Render HTML File

ExpressJS is a popular NodeJS web framework. ExpressJS allows you to develop a custom web server according to your project requirement. The Express project can be extended by installing various node modules. However, you don’t need to install multiple packages to handle HTML files and render them in the response.

This tutorial will teach you how to render HTML files in a custom NodeJS and ExpressJS Server. You don’t need to install extra modules to render an HTML file in Express. Just install express and you are good to go.

Step 1: Install Express

Create a new folder and initialize a new Node project using the following command.

Great. let’s move forward and learn about the function we will use to render HTML files in Express.

Step 2: Using sendFile() function

ExpressJS provides the sendFile() function, which can send HTML files to the browser and is then automatically interpreted by the browser. All we need to do is deliver an appropriate HTML file in every route.

For Example: When the user hits the main URL delivers index.html :

//assuming app is express Object. app.get('/',function(req,res) < res.sendFile('index.html'); >);

Note: This code is for example purposes. It will cause a directory resolution error.

Step 3: Render HTML in Express

Let’s create a simple website consisting of a Home page. We will be using Bootstrap for designing and jQuery for event handling.

Directory Structure:

----- node_modules |--+express ---+ index.html ---+ about.html ---+ index.html --- app.js ----package.json

package.json

< "name": "htmlRender", "version": "1.0.0", "description": "", "main": "index.js", "scripts": < "test": "" >, "keywords": [], "author": "", "license": "ISC", "dependencies": < "express": "^4.16.4" >>

Below is our express server code.

app.js const express = require('express'); const app = express(); const path = require('path'); const router = express.Router(); router.get('/',function(req,res)< res.sendFile(path.join(__dirname+'/index.html')); //__dirname : It will resolve to your project folder. >); router.get('/about',function(req,res)< res.sendFile(path.join(__dirname+'/about.html')); >); router.get('/sitemap',function(req,res)< res.sendFile(path.join(__dirname+'/sitemap.html')); >); //add the router app.use('/', router); app.listen(process.env.port || 3000); console.log('Running at Port 3000');

Below is our “index.html” file.

homepage

Step 4: Render Dynamic HTML using templating engine

In the code shown above, we render static HTML files. However, there are scenarios where we need to render dynamic HTML templates. Before you get confused between static and dynamic templates, let me explain the difference quickly.

In static templates, we cannot pass custom variables and customize the template based on our needs. In dynamic templates, we can pass dynamic variables and render HTML files with different values.

Let’s build a simple project to understand the templating in Express. We will use the pug templating engine which is very popular and recommended by Express as well. We have used Pug for this website as well, in fact, this page is rendered using Pug templates.

Let’s install our dependencies.

Below is our Express server code.

const express = require("express"); const app = express(); const path = require("path"); const router = express.Router(); app.set("view engine", "pug"); app.set("views", path.join(__dirname, "views")); router.get("/", (req, res) => < res.render("index"); >); router.get("/about", (req, res) => < res.render("about", < title: "Hey", message: "Hello there!" >); >); app.use("/", router); app.listen(process.env.port || 3000); console.log("Running at Port 3000");

Observe in routers, we are passing dynamic values to Pug templates. Here is the code of Pug templates residing in the views directory.

html head title Render HTML using PUG body h1 Welcome
html head title= title body h1= message

After running this code, navigate your browser to localhost:3000/about, you should see an HTML output rendered using Pug templates.

Pug output

Awesome. These values can be fetched from a database or any other source and rendered using Pug templates.

Related articles about Databases: Database Tutorials

Further reading

Please read some of our best tutorials.

Conclusion

There are scenarios where you need to develop a web server that delivers HTML files like how your apache does. This can be done in Node.js using the sendFile() method and templating can be done using Pug module. However, this is not the optimal use of Node.js but you can use such a feature to achieve a custom web server for your own application.

Reference

Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Источник

Оцените статью