Node JS require('path') - node.js

I have this problem with the path module. When I try to use "path.join..." inside the request handler, I get the error message
TypeError: Cannot read property 'join' of undefined
However, I can fix it by loading the module inside the body of the requestHandler (I commented it out in the code).
Could you explain why it fails and why the "fix" works and what is the most common way to handle this?
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var port = 3000;
var requestHandler = (request, response) => {
//path = require('path');
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd(), uri);
var path = process.cwd();
var buffer = fs.readFileSync(path + "/someSite.html");
response.end(buffer);
};
var server = http.createServer(requestHandler);
server.listen(port, (err) => {
if (err) {
return console.log('sum ting wong', err);
}
console.log('server is listening on ${port}');
});

It's broken because you're reassigning to path inside your request handler w/ var path = process.cwd().
The var declaration is being hoisted, which means your implementation is equivalent to:
var requestHandler = (request, response) => {
var path; // hoisted!
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd(), uri);
path = process.cwd();
// ...
};

Related

Why did I get Error Cannot Get/ Node.js (in browser)

This is what I have, the filename "pages" actually exists
The code is:
var cors = require('cors');
var express = require('express');
var url = require('url');
var fs = require('fs');
var app = express();
var server = app.listen(3000, function () { console.log('Listening to port 3000') });
app.use(cors());
app.use(express.static('pages'));
app.post('/storeData', storeData);
function storeData(req, res) {
var input = url.parse(req.url, true).query;
var to_save = input.email + ',' + input.password + '\n';
fs.appendFile('./loginDetails.txt', to_save, (err) => {
if (err) console.log('Error occured while storing data!');
res.send('Data stored successfully');
});
}
The Error (in browser):
Cannot GET /
You haven't defined a get route for /. If you try to access a file under pages instead of just the root service, it should work.

How to upload (pdf) file from FileReader to node js Express app

I have a (React) js app that reads a PDF file using FileReader then uses fetch to send it to a node js server running Express. When the request is received on the server side, however, the request body is undefined. What is missing from my code for this to work?
Client side:
function readFile() {
let file = fileInputRef.current.files[0];
const reader = new FileReader();
return new Promise((resolve) => {
reader.onload = function (e) {
resolve(e.target.result);
};
reader.readAsDataURL(file);//readAsDataURL, readAsArrayBuffer, or readAsBinaryString?
});
}
function handleSubmit(event) {
event.preventDefault();
readFile().then((value) => {
fetch('/gen/file', {
method: 'POST',
body: value
})
});
Server side:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const app = express();
const jsonParser = bodyParser.json()
const port = 3000;
app.post("/gen/file", function (req, res, next) {
console.log(req.body);//undefined - Why????
});
app.listen(port, function (err) {
if (err) console.log(err);
});
Client Side:
function getBase64(file,callback){
const reader = new FileReader();
reader.addEventListener('load',()=> callback(reader.result));
reader.readAsDataURL(file);
}
function handleSubmit(event) {
event.preventDefault();
let body = {};
getBase64(file,fileUrl=>{
body.file = fileUrl;
fetch('/gen/file', {
method: 'POST',
body
})
})
Server Side:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const app = express();
const jsonParser = bodyParser.json()
const port = 3000;
const fs = require('fs');
app.post("/gen/file", function (req, res, next) {
console.log(req.body);//undefined - Why????
let file = req.body.file;
let base64 = file.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var buffer = new Buffer.from(base64[2],'base64');
fs.writeFile(__dirname+"/out.jpeg", buffer, 'base64', function (err) {
console.log(err);
});
});

unable to download videos from fb in node js

I am creating a web application using node js that can download videos from facebook, i am getting the url and quality using express using the code below but how can i download it
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
app.get('/', (req,res)=>{
res.sendFile(path.join(__dirname,'templates','index.html'));
});
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/send_data', function(req, res) {
res.send('You sent the name "' + req.body.fbUrl + ' in '+req.body.quality+' Quality".');
if(req.body.quality == "HD")
{
download_video("HD");
}
else if(req.body.quality == "SD")
{
download_video("SD");
}
else if(req.body.quality == "MP3")
{
download_video("MP3");
}
else
{
app.get('/', (req,res)=>{
res.sendFile(path.join(__dirname,'templates','index.html'));
});
}
function download_video(quality)
{
console.log('video is downloading in "'+req.body.quality+'" Quality');
}
I don't know how are you getting the FB video URL explicitly. However, I can help you with how to download video from URL,
let http = require('http');
let fs = require('fs');
let download = (url, dest, cb) => {
let file = fs.createWriteStream(dest);
http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb);
});
});
}
This will create a file stream and download the file chunk by chunk to the destination path (dest).

changing content of fs.createReadstream

I have requirement such that I am reading a file on express request as follows:
const fs = require('fs');
const os = require('os');
const path = require('path');
var express = require("express");
app = express();
app.get('/getdata', function (req, res) {
var stream = fs.createReadStream('myFileLocation');// this location contains encrypted file
let tempVariable = [];
stream.on('data', function(chunk) {
tempVariable += chunk;
});
stream.on('end', function () {
*****here I read tempVariable and using it I decrypt the file content and output a buffer (say,finalBuffer)****
})
stream.on('error', function (error) {
res.writeHead(404, 'Not Found');
res.end();
});
stream.pipe(res);
So what should I do to make the 'finalBuffer' readable on request,in other words, how to pipe the finalBuffer data with res(response).
Finally I got the way for creating read stream from a Buffer using stream of node js.
I got exact solution from here.
I have just put a little bit code like
const fs = require('fs');
const os = require('os');
const path = require('path');
var express = require("express");
app = express();
app.get('/getdata', function (req, res) { // getdata means getting decrypted data
fs.readFile(file_location, function read(err, data) {
// here I am performing my decryption logic which gives output say
//"decryptedBuffer"
var stream = require("./index.js");
stream.createReadStream(decryptedBuffer).pipe(res);
})
})
// index.js
'use strict';
var util = require('util');
var stream = require('stream');
module.exports.createReadStream = function (object, options) {
return new MultiStream (object, options);
};
var MultiStream = function (object, options) {
if (object instanceof Buffer || typeof object === 'string') {
options = options || {};
stream.Readable.call(this, {
highWaterMark: options.highWaterMark,
encoding: options.encoding
});
} else {
stream.Readable.call(this, { objectMode: true });
}
this._object = object;
};
util.inherits(MultiStream, stream.Readable);
MultiStream.prototype._read = function () {
this.push(this._object);
this._object = null;
};
If anybody has some issue with this please comment I will try my best to make him/her understood my code snippet.

resource is not passed - node js

I'm trying to forward created resource (http) by callback to print result on web page using it
var http = require('http');
var net = require('net');
var fs = require ('fs');
var Path = require('path');
function LookDirs(server,port,callback){
http.createServer(function (req, res) {
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.write('<html><head><title>Simple Server</title></head>');
res.write('<body> Test1');
callback('..', res);
res.end('\n</body</html>');
}).listen(port);
};
function ViewContent(dirPath){
fs.readdir(dirPath, function(err, entries){
for (var idx in entries){
var fullPath = Path.join(dirPath, entries[idx]);
(function(fullPath){
console.log(fullPath,idx);
res.write('abc');
})(fullPath);
}
})
}
LookDirs("Test 234", "1337", ViewContent);
And I keep getting
res.write('abc');
^
ReferenceError: res is not defined
I was sure that I have passed that resource during callback..
You can not access res from ViewContent.
This (req, res) responses from createServer stand for request and response. Here you can see more about it: https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/
const server = http.createServer((request, response) => {
// magic happens here!
});
Also you can not run callbacks on createServer prototype, but you can run on the listen method though.
var http = require('http');
var net = require('net');
var fs = require('fs');
var Path = require('path');
function LookDirs(server, port, callback) {
http.createServer(function (req, res) {
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.write('<html><head><title>Simple Server</title></head>');
res.write('<body> Test1');
res.end('\n</body</html>');
}).listen(port, callback("./"));
};
function ViewContent(dirPath) {
fs.readdir(dirPath, function (err, entries) {
for (var idx in entries) {
var fullPath = Path.join(dirPath, entries[idx]);
// I can not access res from here, it has sent already.
console.log(fullPath)
}
})
}
LookDirs("Test 234", "1337", ViewContent);

Resources