Good day StackOverflow, I am currently integrating a credit check SOAP API, I was given some sample code without a package.json file, so I have no idea as to the development environment. Here is the sample code I was given:
var request = require('request');
var fs = require('fs');
var bsplit = require('buffer-split');
//process.env.http_proxy = 'http://host:port';
var xmlData = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webServices/">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
' <web:DoNormalEnquiryStream>' +
' <request>' +
' <pUsrnme>*****</pUsrnme>' +
' <pPasswrd>*****</pPasswrd>' +
' <pVersion>1.0</pVersion>' +
' <pOrigin>QA-SOAPUI</pOrigin>' +
' <pOrigin_Version>1.0</pOrigin_Version>' +
' <pInput_Format>XML</pInput_Format>' +
' <pTransaction>' +
' <![CDATA[<Transactions>' +
' <Search_Criteria>' +
' <CS_Data>Y</CS_Data>' +
' <CPA_Plus_NLR_Data>Y</CPA_Plus_NLR_Data>' +
' <Deeds_Data>N</Deeds_Data>' +
' <Directors_Data>N</Directors_Data>' +
' <Identity_number></Identity_number>' +
' <Surname></Surname>' +
' <Forename></Forename>' +
' <Forename2/>' +
' <Forename3/>' +
' <Gender>M</Gender>' +
' <Passport_flag>N</Passport_flag>' +
' <DateOfBirth>19820914</DateOfBirth>' +
' <Address1></Address1>' +
' <Address2></Address2>' +
' <Address3/><Address4/>' +
' <PostalCode></PostalCode>' +
' <HomeTelCode/>' +
' <HomeTelNo/>' +
' <WorkTelCode/>' +
' <WorkTelNo/>' +
' <CellTelNo/>' +
' <ResultType>JPDF2</ResultType>' +
' <RunCodix>N</RunCodix>' +
' <Adrs_Mandatory>N</Adrs_Mandatory>' +
' <Enq_Purpose>12</Enq_Purpose>' +
' <Run_CompuScore>N</Run_CompuScore>' +
' <ClientConsent>Y</ClientConsent>' +
' </Search_Criteria>' +
' </Transactions>]]>' +
' </pTransaction>' +
' </request>' +
' </web:DoNormalEnquiryStream>' +
' </soapenv:Body>' +
' </soapenv:Envelope>';
request({
url: "api.myapiurl.com/soap-api",
encoding:null,
method: "POST",
headers: {
"content-type": "text/xml"
},
body: xmlData
}, function (error, response, body){
var delim = new Buffer('--uuid');
var result = bsplit(body,delim);
var attBuffs = [];
var attBuffsStartIndex = [];
for(var i = 0; i < result.length; i++){
if(result[i].toString().indexOf("Content-Type: application/octet-stream") > 0){
attBuffs.push(result[i]);
var trimmedString = result[i].toString();
attBuffsStartIndex.push(trimmedString.indexOf("Content-Transfer-Encoding: binary")+37);
}
}
fs.open('JsonFile.json', 'w', function (err, fd) {
if (err) {
throw 'error opening file: ' + err;
}
fs.write(fd, attBuffs[0], attBuffsStartIndex[0], attBuffs[0].length - attBuffsStartIndex[0], null, function (err) {
if (err) throw 'error writing file: ' + err;
fs.close(fd, function () {
console.log('JSON File written to file');
})
});
});
fs.open('PdfFile.pdf', 'w', function (err, fd) {
if (err) {
throw 'error opening file: ' + err;
}
fs.write(fd, attBuffs[1], attBuffsStartIndex[1], attBuffs[1].length - attBuffsStartIndex[1], null, function (err) {
if (err) throw 'error writing file: ' + err;
fs.close(fd, function () {
console.log('PDF File written to file');
})
});
});
});
I am having some difficulty getting this code to run. I thought it might need the [RequireJS API], but after doing some research I strongly believe it's actually the Request HTTP Client. I really struggling to get this sample code running. Any assistance would be greatly appreciated!
Addition
I am aware that this is it requires nodejs. But I have not been able to figure out how to progress from there.
Addition
If anyone is interested native node modules such as net, fs etc are not meant to be run from a browser, so this code will not work anyway.
1. Create a project directory
mkdir ~/projects/credit
(If ~/projects doesn't exist, create it with mkdir ~/projects first or create the new directory wherever you want.)
2. Change to the new directory
cd ~/projects/credit
2. Create a file for your sample code
touch sample.js
3. Paste in your sample code in the sample.js file
4. Install the request and buffer-split packages
npm install request buffer-split
This should generate a package.json file in your new project directory, along with the node_modules directory with the installed modules.
5. Run the file
Assuming you have Node installed...
node sample.js
Related
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
Even though I can clearly see my output in console. I can't write them into a file. There is 1 output file and its undefined-03-02-2017.txt which contains single line '15:33 undefined'.
for (i = 0; i < channelcount; i++) {
messages[i] -= messagesOld[i];
console.log(channels[i] + ' ' + messages[i]);
messages[i] = messagesOld[i];
fs.open('logs/' + channels[i] + '.txt', 'r', function (err, fd) {
if (err && err.code == 'ENOENT') {
fs.writeFile('logs/' + channels[i] + '-' + moment().format('MM-DD-YYYY') + '.txt', moment().format('H:mm') + ' ' + messages[i], function (err) { });
} else {
fs.appendFile('logs/' + channels[i] + '-' + moment().format('MM-DD-YYYY') + '.txt', moment().format('H:mm') + ' ' + messages[i] + '\n', function () { });
}
});
}
fs.open() is an async function. So your entire loop will run before the first callback actually gets called. By that time i equals channelCOount + 1 and channels[ channelCount + 1 ] is undefined.
You can either wrap the callback into a closure, use a let if you can use ES6, or use fs.openSync()
#Pyro, you used writeFile incorrectly. Please see syntax
writeFile(file, data[, options], callback)
you have to use like this
fs.writeFile('logs/' + channels[i] + '-' + moment().format('MM-DD-YYYY') + moment().format('H:mm') + '.txt ' , messages[i], function (err) { });
i want log my user command
function saveLog (nick, command) {
var file = 'log/' + nick + '.log';
var datetime = '[' + getDateTime() + '] ';
var text = datetime + command + '\r\n';
fs.writeFile(file, text, function (err) {
if (err) return console.log(err);
console.log(text);
});
}
the function i made is fine, but
it didnt save the log in new line, its just replace text / rewrite the file.
whats im missing ?
thanks
fs.writeFile writes a WHOLE NEW file. What your are looking for is fs.appendFile which will make the file if it doesn't exist and append to it. Documentation here.
function saveLog (nick, command) {
var file = 'log/' + nick + '.log';
var datetime = '[' + getDateTime() + '] ';
var text = datetime + command + '\r\n';
fs.appendFile(file, text, function (err) {
if (err) return console.log(err);
console.log('successfully appended "' + text + '"');
});
}
I need to upload file and I am using node js in server(version : [nodemon] v1.0.1). The following code worked before 4 months after that I did n't check it and yesterday I run it again. But it is not working and I got "TypeError: Object #<Object> has no method 'existsSync'" error in console. Following is my code
var express = require('express');
var path = require('path');
var app = module.exports = express();
var calenderid;
var EventEmitter = require('events').EventEmitter, https = require('https'), http = require('http'), querystring = require('querystring'), url = require('url');
var path2;
app.configure(function() {
app.use(express.compress());
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.cookieParser());
app.use(express.session({
secret : 'foobar'
}));
app.use(express.bodyParser({
uploadDir : __dirname + '/uploads'
}));
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
var http = require('http');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : '3306',
database : 'db',
user : 'root',
password : '',
});
connection.connect();
var fs = require('fs');
app.post('/file-upload/:id', function(req, res) {
var tble = "image";
var id = req.params.id;
console.log("req.files.files" + JSON.stringify(req.files),
req.files.files.length);
var tmp_path = req.files.files[0].path;
console.log("hiii temp path" + tmp_path, typeof tmp_path);
// var firstIdx =0
var lastidx = tmp_path.lastIndexOf("/");
var path = tmp_path.substring(0, lastidx);
console.log("target path sub" + lastidx, tmp_path);
// var target_path = path+"\"+req.files.files[0].name;
var dirExists = fs.existsSync(__dirname + "/uploads/" + id);
console.log(dirExists);
if (!dirExists) {
fs.mkdirSync(__dirname + "/uploads/" + id);
target_path = path + "/" + id + "/" + req.files.files[0].name;
} else {
target_path = path + "/" + id + "/" + req.files.files[0].name;
}
console.log("hiii target_path" + target_path);
fs.rename(tmp_path, target_path, function(err) {
if (err)
throw err;
// delete the temporary file, so that the explicitly set temporary
// upload dir does not get filled with unwanted files
fs.unlink(tmp_path, function() {
if (err)
throw err;
// res.send('File uploaded to: ' + target_path + ' - ' +
// req.files.files[0].size + ' bytes'+req.files.files.length);
// queryurl = 'SELECT * FROM ' +tble + ' WHERE ' + id;
queryurl = 'SELECT * FROM ' + tble + ' WHERE image=' + '"'
+ req.files.files[0].name + '"' + ' AND branch=' + '"' + id
+ '"';
connection.query(queryurl, function(err, result, fields) {
console.log(JSON.stringify(result) + "result.image");
if (result.length == 0) {
console.log("in if !result");
connection.query('INSERT INTO ' + tble + '(' + 'branch'
+ ',' + 'image' + ')' + 'VALUES' + '(' + '"' + id
+ '"' + ',' + '"' + req.files.files[0].name + '"'
+ ")", function(err, result, fields) {
if (err)
throw err;
else {
res.send('File uploaded to: ' + target_path + ' - '
+ req.files.files[0].size + ' bytes'
+ req.files.files.length);
}
});
} else {
console.log("in else !result");
res.send("duplicate");
}
});
});
});
});
Following is the error that I got from console.
TypeError: Object #<Object> has no method 'existsSync'
at /var/www/jts-web/WebContent/app.js:95:20
at callbacks (/var/www/web/WebContent/node_modules/express/lib/router/index.js:165:11)
at param (/var/www/web/WebContent/node_modules/express/lib/router/index.js:139:11)
at param (/var/www/web/WebContent/node_modules/express/lib/router/index.js:136:11)
at pass (/var/www/web/WebContent/node_modules/express/lib/router/index.js:146:5)
at Router._dispatch (/var/www/web/WebContent/node_modules/express/lib/router/index.js:173:5)
at Object.router [as handle] (/var/www/web/WebContent/node_modules/express/lib/router/index.js:33:10)
at next (/var/www/web/WebContent/node_modules/express/node_modules/connect/lib/proto.js:190:15)
at Object.methodOverride [as handle] (/var/www/web/WebContent/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js:37:5)
at next (/var/www/web/WebContent/node_modules/express/node_modules/connect/lib/proto.js:190:15)
In one site somebody told it will overcome after upgrading node js. But this code was working fine. It is not good if I need to upgrade for each change.
I solved this issue by adding the following code
fs.existsSync = require('path').existsSync;
above
var dirExists = fs.existsSync(__dirname + "/uploads/" + id);
I got solution from this site
As a side note, as I encountered somewhat *similar* issue but on different scenario.
I tried to run grunt for bootstrap.
Here is the error I got:
/home/user/gbootstrap/node_modules/grunt/lib/grunt/file.js:374
return fs.existsSync(filepath);
^
TypeError: Object #<Object> has no method 'existsSync'
at Object.exists (/home/user/gbootstrap/node_modules/grunt/lib/grunt/file.js:374:13)
at Task.init (/home/user/gbootstrap/node_modules/grunt/lib/grunt/task.js:423:31)
at Object.initTasks (/home/user/gbootstrap/node_modules/grunt/lib/grunt/help.js:90:14)
at /home/user/gbootstrap/node_modules/grunt/lib/grunt/help.js:49:55
at Array.forEach (native)
at Object.display (/home/user/gbootstrap/node_modules/grunt/lib/grunt/help.js:49:17)
at Object.tasks (/home/user/gbootstrap/node_modules/grunt/lib/grunt.js:101:10)
at Object.cli (/home/user/gbootstrap/node_modules/grunt/lib/grunt/cli.js:38:9)
at Object.<anonymous> (/home/user/gnode-v0.10.26-linux-x86/lib/node_modules/grunt-cli/bin/grunt:45:20)
at Module._compile (module.js:446:26)
I found the root cause was due to i am using the default debian nodejs package (version 0.6.19) from repository.
Solution:
1. remove the nodejs:
sudo apt-get remove nodejs
2. download the binary from http://nodejs.org/download/
3. use the correct node and npm from the bin folder. Then it runs...
credit to this post:
https://github.com/Crisu83/yii-app/issues/13
Make sure you load the core fs module at the top of this file like var fs = require("fs");. Other that that, existsSync should be there.
Side note: You can't use synchronous IO calls in a network server such as this. It completely destroys node's concurrency model at a basic and fundamental level. Use the async versions. You're already using some of them, just use async version exclusively and you'll be noding correctly.
I want my context menu item to be visible only if the clicked node is a link i.e. and href is either a magnet link or a torrent link. But item is visible for all the links because context function is not executing, can anybody help why context function is not executing?
Here is the code:
exports.main = function() {
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
var clickCode = ' self.on("click", function(node,data){ '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_hash = /[0-9abcdef]{32,40}/i; ' +
' var result = node.href.match(pat_hash); '+
' var hash = "" '
' if(result != null) { hash=result[0]; } '+
' var xhr = new XMLHttpRequest(); '+
' if(hash != "") { '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&info_hash="+hash; '+
' } '+
' else{ '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&url="+encodeURI(node.href); '+
' } '+
' xhr.open("GET",apiCall,true); '+
' xhr.onreadystatechange = function(){ if(xhr.readyState = 4) { if (xhr.response.status = "ok") { alert("Torrent added to Furk."); } else { alert("Torrent could not be added to Furk."); } } } '+
' xhr.send(null); '+
' });';
cm.Item({
label: "Add to Furk",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode + clickCode
});
};
Please always post self-containied examples that can be directly tried in the future.
Now back to your problem: The content script actually has a syntax error.
The following line:
' var pat_torrent = /.torrent$/i ' +
lacks a semicolon, and should be:
' var pat_torrent = /.torrent$/i; ' +
The reason automatic semicolon insertion (ASI) does not work here is: The "code" is actually a string that has no newlines in it whatsoever. If there were newlines, then ASI would have worked.
Anway, another reason not to have complex content script inline. Have a look at contentScriptFile.
This error is actually logged, but the presentation sucks. In the Browser Console:
[20:57:51.707] [object Error] (expandable)
In terminal:
console.error: context-magnet:
Message: SyntaxError: missing ; before statement
Here is a fixed, reproducible sample:
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
cm.Item({
label: "magnet test",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode
});
Edit ' var hash = "" ' has the same problem, and there are might be other such errors that I missed skimming this new code.
As I already said, please use contentScriptFile and not contentScript for long-ish scripts.
Another edit
Here is a builder using contentScriptFile, where I also fixed a couple of other errors, the most important of which are:
Use permissions so that the XHR will work.
Correctly set up the XHR to use responseType and overrideMimeType().
Use onload/onerror instead of onreadystatechange.
When uploaded files using valums ajax uploader we get the list of files with file name and file size. I wanted the list to come with file name, file size and a Delete link for the file. So that when the user clicks on delete the file should get out of the list that are displayed.
I was successful on getting the delete link on each file but as i have less javascript knowledge was unable to process as i wanted. if anybody can help would be great.
This is what i have done uptil now.
function deleteme(id){
//something like this
var item = this._getItemByFileId(id);
qq.remove(this._find(item));
}
fileTemplate:'<li>' +
'<span class="qq-upload-file"></span>' +
'<span class="qq-upload-spinner"></span>' +
'<span class="qq-upload-size"></span>' +
'<a class="qq-upload-cancel" href="#">Cancel</a>' +
'<span class="qq-upload-failed-text">Failed</span>' +
'<a class="qq-upload-del-text" href="javascript:deleteme(this.id);">Delete</a>' +
'</li>',
thanks in advance.
I was using the FileUploaderBasic version and faced the same problem. So I did a DIY remove
Here is the full example:
var $fub = $('#fine-uploader-basic'),
$messages = $('#upload-messages');
// try the basic uploader
var uploader = new qq.FileUploaderBasic({
button: $fub[0],
action: base_ajax_url + 'upload',
debug: true,
autoUpload: false,
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
sizeLimit: 204800, // 200 kB = 200 * 1024 bytes
// the method name really should be onSelect
onSubmit: function(id, fileName) {
var _self = this;
var entry = $('<div id="file-' + id + '" class="alert" style="margin: 10px 0 0">' + fileName + ' <span class="qq-upload-cancel close">×</span></div>'
).appendTo(
$messages[0]
).find('.qq-upload-cancel').click(function() {
_self._storedFileIds.splice(_self._storedFileIds.indexOf(id) , 1);
$($(this).parent()).remove();
return false;
});
},
onUpload: function(id, fileName) {
$('#file-' + id).addClass('alert-info')
.html('<img src="/sites/all/themes/pb_admin/images/loading.gif" alt="Initializing. Please hold."> ' +
'Initializing ' +
'"' + fileName + '"');
},
onProgress: function(id, fileName, loaded, total) {
if (loaded < total) {
progress = Math.round(loaded / total * 100) + '% of ' + Math.round(total / 1024) + ' kB';
$('#file-' + id).removeClass('alert-info')
.html('<img src="/sites/all/themes/pb_admin/images/loader.gif" alt="In progress. Please hold."> ' +
'Uploading ' +
'"' + fileName + '" ' +
progress);
} else {
$('#file-' + id).addClass('alert-info')
.html('<img src="/sites/all/themes/pb_admin/images/loader.gif" alt="Saving. Please hold."> ' +
'Saving ' +
'"' + fileName + '"');
}
},
onComplete: function(id, fileName, responseJSON) {
if (responseJSON.success) {
$('#file-' + id).removeClass('alert-info')
.addClass('alert-success')
.html('<i class="icon-ok"></i> ' +
'Successfully saved ' +
'"' + fileName + '"');
} else {
$('#file-' + id).removeClass('alert-info')
.addClass('alert-error')
.html('<i class="icon-exclamation-sign"></i> ' +
'Error with ' +
'"' + fileName + '": ' +
responseJSON.error);
}
}
});
(The name onSubmit kinda questionable ... anyway)
I tried to call the onCancel method (but throw exception that is undefined).
Then this one works - by remove the id from the _storedFileIds array. And that's it.