Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
Improve this question
I'm fetching a JS file over the network.
ie:
// file is a JS file
// for example: console.log("I am file")
const file = await get('/api/file/1')
I'm not sure how to feed this type of data to fs. I think it needs to be a Buffer but I haven't gotten it to work:
const dataAsBuffer = Buffer.from(file, 'utf-8')
Then I try:
fs.writeFileSync(filePath), dataAsBuffer, (err) => { ...
But get: TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
How can I write a JS file I fetched, to local directory?
EDIT:
the output of get:
// initialize code called once per entity
Test.prototype.initialize = function() {
};
// update code called every frame
Test.prototype.update = function(dt) {
};
console.log('hell oworld');
Fixed: No callback in writeFileSync
Related
This question already has answers here:
Configure Node.js to log to a file instead of the console
(28 answers)
Closed 6 months ago.
i want to write console logs into logs.json file and saves it like:
{
"1":"consolelog1",
"2":"consolelog2",
"3":"consolelog3"
}
Using node.js, you can use fs:
const fs = require('fs');
function log_to_file(mystuff){
// GET file
const file = JSON.parse(fs.readFileSync('./logs.json'));
// Find number of console.logs already there
let lognumb = -1, cont = true;
while(cont){
if(!(file[lognumb+1]===undefined)){
lognumb++;
continue
};
cont=false
};
file[lognumb+1] = "consolelog"+mystuff;
fs.writeFileSync("./logs.json",JSON.stringify(file));
}
Then, you can use log_to_file("your_console_log_data") to save your data.
Make Sure You Are Using NODE.JS, Not JAVASCRIPT
Below code give me the corrupted file please help.
exports.testExcelCreation = async function () {
// construct a streaming XLSX workbook writer with styles and shared strings
const options = {
filename: 'assets/Uploads/Reports/TEST/streamed-workbook.xlsx',
useStyles: true,
useSharedStrings: true
};
const workBook = new ExcelJs.stream.xlsx.WorkbookWriter(options);
const workSheet = workBook.addWorksheet("sheet 1");
console.log("Success");
}
I think you forget add await workbook.commit(); before console.log("Success");
I face the similar problem. I tried to update excel file asynchronously from multiple places in my code simultaneously. If we try to open the file in read mode when it was in write mode already, it'll make the file corrupted.
I was stuck in the below error.
Error Error: Corrupted zip or bug: expected 16 records in central dir, got 0
at ZipEntries.readCentralDir (/node_modules/jszip/lib/zipEntries.js:146:23)
at ZipEntries.load (/node_modules/jszip/lib/zipEntries.js:257:14)
at /node_modules/jszip/lib/load.js:48:24
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async XLSX.load (/node_modules/exceljs/lib/xlsx/xlsx.js:279:17)
at async XLSX.readFile (/node_modules/exceljs/lib/xlsx/xlsx.js:55:24)
I carefully gone through my code and found that I've been asynchronously calling update excel method multiple times simultaneously. I made it to be synchronous and removed unwanted code calling update excel method. This fixes my problem.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to write a unit test over my file routes.js using mocha and chai. I have defined a function in routes.js and has defined a test file in which my test case is there.
When i am running my test case, its showing the error TypeError: Cannot read property 'get' of undefined
My code for test.js is
var expect = require('chai').expect;
var chai = require('chai');
var app = ('../api/smartAccount/identifyLoan/getDirectDebitTrans/routes');
describe("Unit testing for function", function(){
it("Testing the function using mocha", function(done){
var req = {
queryString: 101
};
var test = app.getUser.get(req);
expect(test).to.be.an('undefined');
done();
});
});
I am passing req as i am expecting req.queryString.id in my routes.js .
code of routes.js is
var config = require("../../../../serverConfig/config");
module.exports = {
getUser: {
get: function(req, parameters, environment) {
var id = req.queryString.id;
//functionality
});
}
}
Please help where i am going wrong.
p.s get function is fetching data from DB but i havent mentioned the bd connection as i feel its of irrelevance here.
TIA
Nothing scary here. You are missing the require keyword in test.js's
var app = ('../api/smartAccount/identifyLoan/getDirectDebitTrans/routes');
Hence;
var expect = require('chai').expect;
var chai = require('chai');
var app = require('../api/smartAccount/identifyLoan/getDirectDebitTrans/routes');
Will fix it.
Without the require keyword, variable app is just a string with value of ../api/smartAccount/identifyLoan/getDirectDebitTrans/routes' and the code dies when it tries to access the non-existence get property. And this is evidently shown in your error message TypeError: Cannot read property 'get' of undefined
I have this code:
var file = fs.createWriteStream(_filename, _saveFile);
var request = http.request(options);
var decrypt = Crypto.createDecipheriv('aes-128-cbc', key, iv);
var _saveFile = function(response) {
res.pipe(decrypt).pipe(file);
res.on("end", function() {
file.close();
});
};
file.on("error", function(err) {
console.log("Error while writing file", err);
});
It works ok. But randomly I'm receiving this error:
{ [Error: EBADF, write] errno: 9, code: 'EBADF' }
I read this is because the file is being written after it was closed. So, the question I have is: Am I doing something wrong? Is there any way to do decrypt.on("end")instead of res.on("end")?
MORE INFORMATION
In the same res.on("end") I have a q.defer().resolve call, because this method is downloading several .ts files and then I need to turn them into a MP4.
As #mscdex said, there is no need to close the file, however, if the promise is resolved before the file has been actually finished then, I may be working with a corrupted file. Like this:
Download 1.ts
Download 2.ts
Download 3.ts
Here all the promises are saved in a an array and then I use q.spread to wait for all of them
File 1.ts writted
File 1.ts resolve promise
File 2.ts writted
File 2.ts resolve promise
File 3.ts resolve promise
q.spread knows all the promises were resolved so it starts working with the .ts files
File 3.ts writted
From this point on, I'll be working with a wrong/incomplete file.
You don't need to explicitly call file.close() since the file stream will be closed automatically when upstream ends.
If you need to wait until the file is completely written, listen for the finish event on file:
file.on('finish', function() {
// resolve promise or do whatever
});
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I am using the web-server.js node script to run a webserver on my local machine.
The behavior of web-server.js is to dump a complete file listing if a directory is requested.
instead I would like to emulate the apache DirectoryIndex where by if there is an index.html in the directory it will be served instead.
var fs = require('fs');
http://nodejs.org/api/fs.html You can check for files with this.
I could not find the answer so here is my code that does it.
first I had to change the handleRequest function
if (stat.isDirectory()) {
var indexFile = self.getDirectoryIndex_(path);
if (indexFile)
return self.sendFile_(req, res, indexFile);
return self.sendDirectory_(req, res, path);
}
and here is my implementation to getDirectoryIndex_
StaticServlet.prototype.getDirectoryIndex_ = function(path) {
var result = null;
var files = fs.readdirSync(path);
files.forEach(function(fileName, index) {
if (fileName.match(/^index\./gi)) {
result = path + fileName;
return false; //break foreach loop
}
});
return result;
};