I am trying to use host the following js file using nodejs as my first time. The following is the beginning of code to it. I had to use JSDOM since I was trying to use the buttons from the blog.html file in here. The file 'index.html' is present in the folder public and when I run it on terminal, I see the message 'hosting' but it says 'cannot GET /'. Here is my code:
var request = require('request');
const express = require('express');
const app =express();
app.listen(3000, ()=>console.log('hosting'));
app.use(express.static('public' ));
app.get('./blog.html', function(request, response) {
response.sendFile('blog.html');
});
var jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { document } = (new JSDOM('blog.html')).window;
global.document = document;
const postBtn1 = document.getElementById("post-btn1");
const postBtn2 = document.getElementById("post-btn2");
const postBtn3 = document.getElementById("post-btn3");
Related
The following code creates a simple local server that serves specified file to other devices on the same network from 192.168.0.x:8080:
The problems:
Not sure how to stop the server once the file is downloaded on another device
it throws an error if the specified file's name contains non-English characters: Uncaught TypeError: The header content contains invalid characters
download speed is under 25mb/s. Is it because of the method used?
I'm using Node.js HTTP module because I cannot use express module, because webpack throws this error when I require('express'):
./node_modules/http-errors/node_modules/statuses/index.js
Module build failed: Error: ENOENT: no such file or directory,
open 'C:\pathToProject\node_modules\http-errors\node_modules\statuses\index.js'
Question:
Is there a better way to do it?
Code:
const fs = require('fs')
const http = require('http')
const os = require('os')
const path = require('path')
startServer() {
// GETTING NETWORK IP OF THE SERVER (ipv4, e.g. 192.168.0.x)
var interfaces = os.networkInterfaces()
var addresses = []
for (var k in interfaces) {
for (var k2 in interfaces[k]) {
var address = interfaces[k][k2];
if (address.family === 'IPv4' && !address.internal) {
addresses.push(address.address)
}
}
}
var filtered = addresses.filter(x => x.includes("192.168.0"))
// SERVING FILE FOR OTHER LOCAL DEVICES
const hostname = filtered
const port = 8080
var fileName = "1.png"
var filePath = path.join("C:/Users/u/Desktop", fileName)
const server = http.createServer((req, res) => {
var stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
"Content-Disposition": "attachment; filename=" + fileName
});
var readStream = fs.createReadStream(filePath);
// replacing all the event handlers with a simple call to readStream.pipe()
readStream.pipe(res);
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
}
I currently have a massive node JS file (3100+ line of code) and I am trying to split it up into multiple files. I have taken one of the functions and a bunch of firebase database references and put them into their own file inside their own class. For some reason the Firebase references give me an error no matter what even when the syntax seams to be okay:
/.../lib/context.js:13
static database = firebase.database()
^
SyntaxError: Unexpected token =
Here is my code for importing the file
// index.js
'use strict'
var ... = ...()
...
var util = require('util')
var fs = require('fs')
var http = require('http')
var firebase = require('firebase')
var Context = require('./lib/context.js')
and here is my code of the imported file:
'use strict'
var util = require('util')
var firebase = require('firebase')
exports.Context = class
{
constructor()
{
}
static database = firebase.database()
static homeworkRef = database.ref("/homework")
static usersRef = database.ref("/users")
static announcementsRef = database.ref("/announcements")
static votingRef = database.ref("/voting")
static feedbackRef = database.ref("/feedback")
static peerRef = database.ref("/peer_review")
Am I requiring the file correctly? Why does this error keep happening? It worked fine while it was in one file.
i want to access a model name userRegistration in my custom js file but every time its showing undefined and shows this error
TypeError: Cannot call method 'findOne' of undefined
please Check code
var loopback = require('loopback');
var app = loopback();
var nodemailer = require("nodemailer");
var smtpTransport = require("nodemailer-smtp-transport");
var path=require('path');
var fs=require('fs');
var Handlebars = require('handlebars');
exports.mailToUser=function(req,res,next){
var userNotification = app.models.UserNotification;
var userregister = app.models.UserRegistration;
userregister.findOne({where:{email:email}},function(err,userobj){
if(err){
next()
}
})
}
Thanks
You shouldn't use var app = loopback();
If you want to access to app you can require your server.js or some other ways existed. The simple one is requiring server
My export code
//export.js
var express = require('express'),
fs = require('fs'),
request = require('request'),
cheerio = require('cheerio'),
app = express();
var episode = [],
title = [],
synopsis = [],
reviews = [],
date = [];
exports.showGrab = function(url,response){
request(url,response, function(error, response, html){
var $ = cheerio.load(html),
shows = {bitten:['http://www.tv.com/shows/bitten-2013/episodes/']};
$('.no_toggle._clearfix').eq(1).filter(function(){
var data = $(this);
episode = data.children().first().children().last().text();
exports.episode = episode;
})
})
}
console.log(episode); // => defined as [] not the value given in the function
//import.js
var express = require('express'),
fs = require('fs'),
request = require('request'),
cheerio = require('cheerio'),
app = express(),
server = require('./export');
console.log(server.episode);
server.showGrab('http://www.tv.com/shows/bitten-2013/episodes/');
within the import script using the function server.showGrab works fine but I need access to the variables within the show grab function in my import script. I believe this problem boils down to a scope issue, if I export variables outside a function they work fine but I was under the impression that declaring variables the way I have done would make them global. How can I run this function in the import script whilst still passing it a url and getting back episode to work with?
#Pointy you were right the import script was calling the value before it was defined
//import.js
if (server.episode === undefined){
var test = setInterval(function(){
if (server.episode != undefined){
clearInterval(test);
}
console.log(server.episode);
}, 1000);
}
this does the trick, for some reason using else instead of wrapping an if in an if does not work.
I am new to javascript and I would like to specify a javascript program to read from a file and print the contents of the file to a console?.This is the code I have written below and am getting an error,please what's wrong with it?
var express = require('express');
var app = express.createServer(express.logger());
app.get('/',function(request,response){
var fs = require('fs');
var buffer = new Buffer(fs.readFileSync('index.html','utf8'));
response.send(Buffer.toString());
});
var port = process.env.PORT || 5000;
app.listen(port,function()
{
fs.readFileSync();
console.log("Listening on"+ port);
}
);
Use the readFile method of the fs object to read the file, then use console.log to print it:
/* File System Object */
var fs = require('fs');
/* Read File */
fs.readFile('foo.json', bar)
function bar (err, data)
{
/* If an error exists, show it, otherwise show the file */
err ? Function("error","throw error")(err) : console.log(JSON.stringify(data) );
};
For instance, if it is named loadfiles.js, run it as such:
node loadfiles.js