export array to csv Nodejs - node.js

I'm trying to export an array of data to a CSV file in Nodejs. I'm using the NodeCSV module, but I just get errors every time I try to follow the examples and documentation. It prints a bunch of code and says stringifier has no method 'indexOf' when I try to use the stringifier and it says 'object is not a function' when I try
csv().from.array(results).to('/temp/users.csv')
It doesn't work if I take the () off csv either. Does anyone know how to do this or can point me to some good documentation?

Hope it help you more:
http.createServer(function(request, response) {
response.setHeader('Content-disposition', 'attachment; filename=testing.csv');
response.writeHead(200, {
'Content-Type': 'text/csv'
});
csv().from(data).to(response)
})
.listen(3000);

Related

Node JS : invalid data error using execFileSync

I am stuck on a NodeJS error while trying to execute a script and get the output of it.
I get the following error :
TypeError: invalid data
at WriteStream.Socket.write (net.js:623:11)
at Object.execFileSync (child_process.js:482:20)
at doRender (/test/apps/application/routes/TEST.js:1786:26)
I guess it comes from a misuse of the NodeJS native execFileSync function, but I've tried a lot of things to match the documentation without any success so far.
Here is my code :
router.get("/stat", authReader, function (req, res) {
//Current file is in application/routes
var doRender = function (req, res) {
var output;
//I want to execute application/scripts/test.bash
output= child_process.execFileSync("test.bash",[], {
cwd: "../scripts"
});
result= processDataFromCSV(output);
//processing data in response
res.render(acronym + "_test", {
title: "CSV output",
result: result,
});
}
doRender(req, res);
}
Could you please help me to understand what I am doing wrong ? Any help is greatly appreciated.
Verify that your test.bash is executable, or run it like /bin/bash test.bash using child_process.execSync(). For more information look at this answer by Sravan here;

pipe file directly from file system

I'm using "express": "^4.13.3" on node 6.9.0
When i try to pipe data a jpeg image:
const path = config.storageRoot + '/' + req.params.originalFileName;
var mimetype = mime.lookup(req.params.originalFileName);
res.writeHead(200, { 'Content-Type': mimetype});
fs.createReadStream(path).pipe(res);
i get xml data inside the result:
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.5-c014 79.151739, 2013/04/03-12:12:15 ">
When i use res.end with the result from a fs.readFile instead, the binary content is formatted correctly.
What am i doing wrong?
Take a look how I'm piping files in the examples in this answer:
How to serve an image using nodejs
It's something like this:
// 'type' is the MIME type
var s = fs.createReadStream(file);
s.on('open', function () {
res.set('Content-Type', type);
s.pipe(res);
});
s.on('error', function () {
res.set('Content-Type', 'text/plain');
res.status(404).end('Not found');
});
So I'm just setting the header to be posted by Express instead of posting the headers explicitly. Also I'm handling the stream events. Maybe you should try doing it similarly because the way I did it seems to work, according to Travis:
https://travis-ci.org/rsp/node-static-http-servers
Another thing in addition to handling the stream events and errors would be to make sure that you have the correct encoding, permissions etc. I don't know what result are you expecting and what that XML means or where it comes from, but handling the stream events may tell you more about what is happening.

Unable to use getElementsByTagName("body")

Here's the code that results in an error each time I run it. My goal is to scrap the content from the URL, remove all HTML, and return it:
console.log("Fetching: " + inputData.tweeturl);
fetch(inputData.tweeturl)
.then(function(res) {
return res.text();
}).then(function(body) {
var rawText = body.getElementsByTagName("body")[0].innerHTML;
var output = { id: 100, rawHTML: body, rawText: rawText };
callback(null, output);
})
.catch(callback);
The problem is with var rawText = body.getElementsByTagName("body")[0].innerHTML;
The error I receive is:
Bargle. We hit an error creating a run javascript. :-( Error:
TypeError: body.getElementsByTagName is not a function eval (eval at (/var/task/index.js:52:23), :16:24) process._tickDomainCallback (node.js:407:9)
Unfortunately - there is no JS DOM API in the Code by Zapier triggers or actions (that is because it isn't run in a browser and doesn't have the necessary libraries installed to fake it).
You might look at Python and instead, and https://docs.python.org/2/library/xml.etree.elementtree.html. Decent question and answer is available here Python Requests package: Handling xml response. Good luck!
Any function not supported by Zapier will result in a TypeError. I needed to use a regular expression to achieve this.

Nodejs upload a model to shapeways api

I am trying to upload a obj file to shapeways api. I tried using the request module by creating the url. It doesn't seem to be working. Could someone show me some code examples? The documentation only mentions php
Thanks
fs.readFile("/models/temp.obj",function(err,data){
var params = {file:data,
filename:"temp.obj",
hasRightsToModel: 1,
acceptTermsAndConditions: 1}
var client = new shapeways.client({ consumerKey: config.app.key,
consumerSecret: config.app.secret,
oauthToken: req.session.oauthToken,
oauthSecret: req.session.oauthSecret, });
client.addModel(params,callback);
})
Here's the code. The fs.readfile returns undefined.
Looks like your code has two issues.
One you don't specify your root dir, I doubt you really mean /models.
And two you should never ignore the err parameter.
fs.readFile(__dirname + "/models/temp.obj", function (err, data) {
if (err) {
throw err;
}
// . . .
});
My params had filename. It should have been fileName. Silly mistake. Everything else I had incorporated anyways. Thanks for all your help.

Blank output with mustache template, connect & node.js

I'm just getting into this whole node.js business and like it so far; however I've run into an issue involving connect/mustach.
Here's the code for a simple one page app; at this point I'm really just trying to get the app to use my mustache templates so that I can take it from there.
var connect = require("connect"),
fs = require("fs"),
mustache = require("mustache");
connect(
connect.static(__dirname + '/public'),
connect.bodyParser(),
function(req, res){
var data = {
variable: 'Some text that I'd like to see printed out. Should in the long run come from DB.'
},
htmlFile = fs.createReadStream(
__dirname + "/views/index.html",
{ encoding: "utf8" }
),
template = "",
html;
htmlFile.on("data", function(data){
template += data;
});
htmlFile.on("end", function(){
html = mustache.to_html(template, data);
})
res.end(html);
}
).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
My problem here is that the above code generates a blank webpage.
If I log the html-variable I get two outputs of the html with the variable text attached in it, so the to_html-function seems to do it's job. And if I do res.end('some string'); the string is displayed in the browser as it should.
The template is a plain old .html-file with a <p>{{variable}}</p>-tag in its body.
Any idea what's wrong?
Your problem is that you're not using async code correctly. By the time res.end(html) gets called the file is not yet read. Correct usage:
htmlFile.on("end", function(){
html = mustache.to_html(template, data);
res.end(html);
})
Also you should take care of the syntax error: variable: 'Some text that I'd like to see printed out. Should in the long run come from DB.'
(misuse of ')

Resources