I have my files object on back-end:
[{ Id: 3,
UserId: 7,
FileType: 'application/pdf',
FileContent:
<Buffer 25 50 44 46 2d 31 2e 33 0d 0a 25 e2 e3 cf d3 0d 0a 0d 0a 31 20 30 20 6f 62 6a 0d 0a 3c 3c 0d 0a 2f 54 79 70 65 20 2f 43 61 74 61 6c 6f 67 0d 0a 2f 4f ... >,
FileName: '1',
UserUploadId: 7 },
...]
I am sending this object to the view:
res.render('dashboard/files/index',{'title': 'My files', 'my_files' : files})
On HTML I am rendering with handlebarsjs a table containing a row per file and a button that executes a function receiving as unique parameter the file Id
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">UserId</th>
<th scope="col">View</th>
</tr>
</thead>
<tbody>
{{#each my_files}}
<tr>
<td>{{this.UserId}}</td>
<td>
<button onclick="viewPdf({{this.Id}})"></button>
</td>
</tr>
{{/each}}
</tbody>
</table>
In the same document, with JavaScript, I am trying to get the FileContent property of the object, but for this I need to find the file in the array my_files searching by Id parameter.
<script>
function viewPdf(Id){
var found_file = my_files.find(function(element) {
return element.Id == Id;
});
console.log(found_file)
}
</script>
But I am getting this error output:
Uncaught ReferenceError: my_files is not defined
at viewPdf (......:465)
at HTMLButtonElement.onclick
So,
JavaScript running server and browser side is different. You can't find a declared server side variable in the browser, vice versa.
A way to shared variable between server and client :
function viewPdf(Id){
$.ajax('/getFiles', {
success:function(my_files){
// put logic here
}
})
}
Related
This question already has answers here:
Why does Node.js' fs.readFile() return a buffer instead of string?
(8 answers)
Closed 12 months ago.
var fs = require('fs');
fs.readFile('TestFile.txt', function (err, data) {
if (err) throw err;
console.log(data);
});
//TestFile.txt This is test file to test fs module of Node.js
Iam getting buffer and hex codes in place of console data
<Buffer 54 68 69 73 20 69 73 20 74 65 73 74 20 66 69 6c 65 20 74 6f 20 74 65 73 74 20 66 73 20 6d 6f 64 75 6c 65 20 6f 66 20 4e 6f 64 65 2e 6a 73>
According to the documentation :
If no encoding is specified (using options.encoding), the data is returned as a <Buffer> object. Otherwise, the data will be a string.
Solution : add an encoding (and read the doc! :)
fs.readFile('TestFile.txt', { encoding : 'utf8' } , function()...
By converting data to String(data) you will get text
I am sending a JSON file over http. The file is available on req.files using the express-fileupload middleware. I am getting the file as a buffered data. I want to convert the file to a JSON object.
app.post('/start', function(req, res){
if(!req.files.seed)
res.status(400).send("Please upload the seed file");
var file = req.files.seed;
var obj = //Convert the file to JSON object and send it to create instance;
instance.createInstance(obj);
res.status(200).send("Started....");
});
When printed, the file looks like something this
{ name: 'seed.json',
data: <Buffer 7b 0d 0a 09 22 61 72 72 61 79 22 3a 20 5b 20 31 2c 20 31 20 5d 2 c 0d 0a 09 22 72 65 63 75 72 72 65 6e 63 65 22 3a 20 7b 0d 0a 09 09 22 73 65 63 6f 6e ... >,
encoding: '7bit',
mimetype: 'application/json',
mv: [Function: mv] }
I tried using JSON.parse(file) but SyntaxError: Unexpected token o in JSON at position 1 pops up.
I also tried using converting it to a string using
var text = file.toString(file,'utf8')
var obj = JSON.parse(text)
but this also doesn't seem to work. The properties of this objects, when accessed are undefined.
The JSON file structure.
{
"array": [ 1, 1 ],
"recurrence": {
"second": 50,
"minute": null,
"hour": null,
"dayOfweek": null
},
"campaign": {
"sender": "StartUp India Yatra",
"email": "fashion#getposhaq.com",
"subject": "{Invitation} StartUp India Yatra Chapter",
"title": "StartUp India Yatra Campaign"
},
"condition": {
"open": {
"greaterThanEqual": 1,
"lessThan": 2
},
"campaignSummary": null
},
"textPath": "../template.txt",
"htmlPath": "../template.html",
"path": "../emailer/index.js"
"retailerId": "4"
}
Given what you presented in the debug, your encoding is not utf8 but 7bit. So for a proper decoding you will need to change a bit your code.
var file = req.files.seed;
var obj = JSON.parse(file.data.toString('ascii'));
// ... do your creation logic
Any way you can play with the utf8, ascii econdings to see if you do not have JSON.parse problems.
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
I am running this code, which should compare saved webpages with the current live versions, but it seems to only do so for the last entry:
ipcMain.on('compare', (event, arg) => {
index.find({
"type": "website"
}, function(err, docs) {
var doc;
var data;
for (i = 0; i < docs.length; i++) {
console.log(doc = docs[i]);
console.log(i);
request('GET', doc.URL).done(function(res) {
data = fs.readFileSync(DataPath + "/savedpages/" + doc.Name + ".html");
console.log(data);
console.log(res.getBody())
if (data == res.getBody()) {
index.update({
_id: doc.ID
}, {
$set: {
Changes: false
}
}, function(err, updateval) {
if (err) throw err;
console.log(doc.Name);
event.sender.send('update-false', doc.Name + "-changescell")
})
} else {
index.update({
_id: doc.ID
}, {
$set: {
Changes: true
}
}, function(err, updateval) {
if (err) throw err;
console.log(doc.Name);
event.sender.send('update-true', doc.Name + "-changescell")
})
}
})
}
})
})
The output looks like this:
{ Changes: false,
type: 'website',
Date: 2017-07-30T14:04:35.592Z,
Name: 'petra',
URL: 'http://petra.oldisoft.de',
_id: 'SXtHgqAWniDBAibJ' }
0
{ Changes: false,
type: 'website',
Date: 2017-07-30T14:03:26.658Z,
Name: 'heise',
URL: 'http://heise.de',
_id: 'zOc1Wnm801huVPjs' }
1
<Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 6c
61 6e 67 3d 22 64 65 22 3e 0a 0a 3c 68 65 61 64 3e 0a 20 20 20 20 3c 74 69
74 6c ... >
<Buffer 3c 2f 68 65 61 64 3e 0a 3c 62 6f 64 79 20 6f 6e 6c 6f 61 64 3d 27 6a
61 76 61 73 63 72 69 70 74 3a 64 6f 63 75 6d 65 6e 74 2e 61 6e 6d 65 6c 64
75 6e ... >
heise
<Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 6c
61 6e 67 3d 22 64 65 22 3e 0a 0a 3c 68 65 61 64 3e 0a 20 20 20 20 3c 74 69
74 6c ... >
<Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 6c
61 6e 67 3d 22 64 65 22 3e 0a 0a 3c 68 65 61 64 3e 0a 20 20 20 20 3c 74 69
74 6c ... >
heise
It seems to me that the code skips a part of the code while the for loop is running. I don't understand why it is behaving as such.
this is because you are running async code in a loop.
To overcome this you need to create a closure by wrapping the async code in a function:
for(i = 0; i < docs.length; i++){
console.log(doc = docs[i]);
console.log(i);
runAsyncCode(doc)
}
function runAsyncCode(doc){
request('GET', doc.URL).done(function(res) {
data = fs.readFileSync(DataPath + "/savedpages/" + doc.Name + ".html");
console.log(data);
console.log(res.getBody())
if(data == res.getBody()){
index.update({_id: doc.ID}, {$set: {Changes:false}}, function(err, updateval){
if(err) throw err;
console.log(doc.Name);
event.sender.send('update-false', doc.Name + "-changescell")
})
} else {
index.update({_id: doc.ID}, {$set: {Changes:true}}, function(err, updateval){
if(err) throw err;
console.log(doc.Name);
event.sender.send('update-true', doc.Name + "-changescell")
})
}
})
}
I am using AJAX POST data to server which use Node.js code. Very briefly, two file in this test project. Here is main.html:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', '/', true);
xhr.send('hello');
</script>
</body>
</html>
Here the server code:
const http = require('http');
http.createServer(function(req,res) {
console.log(req.body);
}).listen(3000);
Perhaps,you have known that server will console.log() 'undefined'.
So the question is why it's 'undefined'? How to get AJAX data on server?
I know other solution according to this question.
Could you help me any other way to get data conveniently?
You've created server allright, but there's two problems:
Connection endpoint. Your AJAX is POST, so you need to parse POST requests correctly (not exactly solves your issue, but you need to distinguish request methods).
Node.js is not parsing your POST body by default, you need to tell it how it's done, by using querystring module, for example.
Combining this together:
var qs = require('querystring');
http.createServer(function(req, res) {
if (request.method == 'POST') {
var body = '';
request.on('data', function(data) {
body += data;
});
request.on('end', function() {
var post = qs.parse(body);
// Use your POST here
console.log(post);
});
}
}).listen(3000);
JSON data - cleaner solution:
You need to encode your AJAX data with JSON, and than parse it on the server side like this:
http.createServer(function(req,res) {
if (req.method == 'POST') {
var jsonPost = '';
req.on('data', function(data) {
jsonPost += data;
});
req.on('end', function() {
var post = JSON.parse(jsonPost);
// Use your POST here
console.log(post);
});
}
}).listen(3000);
You'd be even better off using Express.js framework for that, with it's bodyParser module.
UPDATE - How chunks are buffered:
Consider simple example - send in xhr.send() a LARGE amount of text, that exceeds Content-Length. Than do the following on data event:
req.on('data', function(data) {
console.log(data);
body += data;
});
You will see something like:
<Buffer 0a 0a 4c 6f 72 65 6d 20 69 70 73 75 6d 20 64 6f 6c 6f 72 20 73 69 74 20 61 6d 65 74 2c 20 63 6f 6e 73 65 63 74 65 74 75 72 20 61 64 69 70 69 73 63 69 ... >
<Buffer 65 74 20 71 75 61 6d 20 63 6f 6e 67 75 65 20 6c 6f 62 6f 72 74 69 73 2e 20 50 65 6c 6c 65 6e 74 65 73 71 75 65 20 74 65 6d 70 75 73 20 75 6c 6c 61 6d ... >
<Buffer 61 2e 20 56 69 76 61 6d 75 73 20 76 69 74 61 65 20 61 6e 74 65 20 6d 65 74 75 73 2e 20 4d 61 75 72 69 73 20 71 75 69 73 20 61 6c 69 71 75 65 74 20 65 ... >
That shows that the data received in chunks on data event. Only on end event you will get the whole data sent (if you've aggregated it before that). Node.js doesn't handle this, that's why you need third-party modules.
That is - you cannot just get req.body of the request, as it wasn't set at all.
I am implementing websocket v07 server protocol in C/C++. It's pretty easy and I have almost coded it. Though I can't understand what mean numbers in first initial packet (not handshake)? Client uses "socket.io" framework. So client sends Date and server answer with another number. I think its something like checksum. Can anyone explain me please how to generate answer and what does it mean?
Examples:
client GET./socket.io/1/?t=1322647367092&jsonp=0
server 52 io.j[0]("1880965230667822746 :15:25:websocket,htmlfile,xhr-polling,jsonp-polling");
client GET./socket.io/1/?t=1322647141334&jsonp=0
server 52 io.j[0]("7826289221657265491 :15:25:websocket,htmlfile,xhr-polling,jsonp-polling");
1322647367092 - Date, server answer - 1880965230667822746
1322647141334 - Date, server answer - 7826289221657265491
My Packet ->
000000 48 54 54 50 2F 31 2E 31 | 20 32 30 30 20 4F 4B 0D HTTP/1.1.200.OK.
000010 0A 43 6F 6E 74 65 6E 74 | 2D 54 79 70 65 3A 20 61 .Content-Type:.a
000020 70 70 6C 69 63 61 74 69 | 6F 6E 2F 6A 61 76 61 73 pplication/javas
000030 63 72 69 70 74 0D 0A 43 | 6F 6E 6E 65 63 74 69 6F cript..Connectio
000040 6E 3A 20 6B 65 65 70 2D | 61 6C 69 76 65 0D 0A 54 n:.keep-alive..T
000050 72 61 6E 73 66 65 72 2D | 45 6E 63 6F 64 69 6E 67 ransfer-Encoding
000060 3A 20 63 68 75 6E 6B 65 | 64 0D 0A 0D 0A 35 30 0D :.chunked....50.
000070 0A 69 6F 2E 6A 5B 30 5D | 28 22 32 37 38 38 39 39 .io.j[0]("278899
000080 38 30 38 38 32 36 32 34 | 38 38 30 3A 31 35 3A 32 80882624880:15:2
000090 35 3A 77 65 62 73 6F 63 | 6B 65 74 2C 68 74 6D 6C 5:websocket,html
0000A0 66 69 6C 65 2C 78 68 72 | 2D 70 6F 6C 6C 69 6E 67 file,xhr-polling
0000B0 2C 6A 73 6F 6E 70 2D 70 | 6F 6C 6C 69 6E 67 22 29 ,jsonp-polling")
0000C0 3B 0D 0A 30 0D 0A 0D 0A ;..0....
Original Packet ->
000000 48 54 54 50 2F 31 2E 31 | 20 32 30 30 20 4F 4B 0D HTTP/1.1.200.OK.
000010 0A 43 6F 6E 74 65 6E 74 | 2D 54 79 70 65 3A 20 61 .Content-Type:.a
000020 70 70 6C 69 63 61 74 69 | 6F 6E 2F 6A 61 76 61 73 pplication/javas
000030 63 72 69 70 74 0D 0A 43 | 6F 6E 6E 65 63 74 69 6F cript..Connectio
000040 6E 3A 20 6B 65 65 70 2D | 61 6C 69 76 65 0D 0A 54 n:.keep-alive..T
000050 72 61 6E 73 66 65 72 2D | 45 6E 63 6F 64 69 6E 67 ransfer-Encoding
000060 3A 20 63 68 75 6E 6B 65 | 64 0D 0A 0D 0A 35 30 0D :.chunked....50.
000070 0A 69 6F 2E 6A 5B 30 5D | 28 22 33 38 34 35 36 31 .io.j[0]("384561
000080 33 32 31 33 36 32 32 39 | 34 30 37 3A 31 35 3A 32 32136229407:15:2
000090 35 3A 77 65 62 73 6F 63 | 6B 65 74 2C 68 74 6D 6C 5:websocket,html
0000A0 66 69 6C 65 2C 78 68 72 | 2D 70 6F 6C 6C 69 6E 67 file,xhr-polling
0000B0 2C 6A 73 6F 6E 70 2D 70 | 6F 6C 6C 69 6E 67 22 29 ,jsonp-polling")
0000C0 3B 0D 0A 30 0D 0A 0D 0A ;..0....
It is a "session ID" according to the socket.io protocol specification:
The body of the response should contain the session id (sid) given to the client, followed by the heartbeat timeout, the connection closing timeout, and the list of supported transports separated by :