Node fs.writefile with absolute path - javascript

I have a node application that emits HTML files. This is the jest of how it works:
const fs = require('fs');
const outputPath = './dist/html/';
// code that generates names and content
const currentFile = `${outputPath}${name}.html`;
const content = '...';
fs.promises.writeFile(currentFile, content, 'utf8');
This works as intended, but generally it is a bad practice to write relative path this way (this works on Mac but probably would not work on Windows machine).
const fs = require('fs');
const path = require('path');
const outputPath = path.join(__dirname, 'dist', 'html');
// code that generates names and content
const currentFile = path.join(outputPath, `${name}.html`);
const content = '...';
fs.promises.writeFile(currentFile, content, 'utf8');
This works, but it creates an entire path (User/my.name/Documents/projects/my-project/dist/html/my-file.html) within my project, since fs.writeFile writes the file relative to the working directory.
Can I make fs write file to the absolute path? Alternatively, what is the proper way of generating relative paths?
I ended up using
const outputPath = `.${path.delimiter}dist${path.delimiter}ads${path.delimiter}`;
But this does not seem like the best possible solution.

according to the docs, 'fs' module works with both relative and absolute paths.
i guess you issue was somehow related to path building.
here is the working code:
const { promises: fsp } = require('fs');
const { join } = require('path');
const fileName = 'file.html';
const content = '...';
(async () => {
try {
await fsp.writeFile(join(process.cwd(), 'dist', 'html', fileName), content);
} catch (error) {
// handling
}
})();

Related

How To Write and Read JSON texts on single file

I'm receiving events in JSON format via a POST route, I would like to save these events in a file like 'example.json' and be able to query it.
I tried using writeFileSync, but it rewrites the entire file. With the flag {flag: 'a+'} I was able to save more than one record, but when I try to require 'example.json', I get an error 'Unexpected token { in JSON'.
Works fine when the file has only one record, but gives the error after the second one.
Code:
const filePath = './example.json';
const fs = require('fs');
const file = require('./example.json');
app.post('/events', (request, response) => {
response.send(request.body);
const contentString = JSON.stringify(request.body);
return fs.writeFileSync(filepath, contentString, {flag: 'a+'});
});
example.json that works:
{"type":"call.new","call_id":"71252742562.40019","code":"h9e8j7c0tl0j5eexi07sy6znfd1ponj4","direction":"inbound","our_number":"1130900336","their_number":"11999990000","their_number_type":"mobile","timestamp":"2020-04-01T00:00:00Z"}
example.json (with two records) that stop working:
{"type":"call.new","call_id":"71252742562.40019","code":"h9e8j7c0tl0j5eexi07sy6znfd1ponj4","direction":"inbound","our_number":"1130900336","their_number":"11999990000","their_number_type":"mobile","timestamp":"2020-04-01T00:00:00Z"}{"type":"call.ongoing","call_id":"71252731962.40019","code":"h9e8j7c0tl0j5eexi07sy6znfd1ponj4","direction":"inbound","our_number":"1130900336","their_number":"11999990000","their_number_type":"mobile","timestamp":"2020-04-01T00:00:00Z"}
How can I write this JSON in a readable form? That does not present the error above and it is possible to perform the require.
Could someone help me, please?
Try to read the JSON file, parse it, add new elements to the array and then overwrite the file.
const fs = require("fs");
const path = require("path");
const FILE_PATH = path.join(__dirname, "./elements.json");
const file = fs.readFileSync(FILE_PATH);
const elements = JSON.parse(file);
const newElement = { id: Date.now() };
const updatedElements = [...elements, newElement];
fs.writeFileSync(FILE_PATH, JSON.stringify(updatedElements));
See more here: https://nodejs.org/api/fs.html#fsappendfilesyncpath-data-options

How to compress Folder in nodeJS Mac without .DS_STORE

Using the folder-zip-sync npm library and other zipping libraries, The .zip file gets saved with an extra .DS_STORE file. How to zip without this file? Is there a setting I can turn off? How to go about this?
var zipFolder = require("folder-zip-sync");
zipFolder(inputPath, pathToZip);
you don't need any library to compress
for this action use node js build in zlib module
const { createReadStream, createWriteStream } = require('fs');
const { createGzip } = require('zlib');
const inputFile = "./input.txt";
const outputFile = "./input.txt.gz";
const srcStream = createReadStream(inputFile)
const gzipStream = createGzip()
const destStream = createWriteStream(outputFile)
srcStream.pipe(gzipStream).pipe(destStream)

Not able to read files content inside NodeJS

I have some markdown files inside /markdown folder. I am trying to read content of these files. I can see the file names inside the array. But when I try to read it, it doesn't return any data or error. What needs to be done here?
app.get("/", async(req, res) => {
const mdPath = "...path"
const data = await fs.readdirSync(mdPath);
console.log(data) // Return Array of files
for (let i = 0; i <= data.length; i++) {
const fileContent = fs.readFileSync(i, "utf-8");
return fileContent;
}
})
You should use something like path() to better handle the filesystem side.
This could work your way:
const fs = require('fs') // load nodejs fs lib
const path = require('path') // load nodejs path lib
const mdPath = 'md' // name of the local dir
const data = fs.readdirSync(path.join(__dirname, mdPath)) //join the paths and let fs read the dir
console.log('file names', data) // Return Array of files
for (let i = 0; i < data.length; i++) {
console.log('file name:', data[i]) // we get each file name
const fileContent = fs.readFileSync(path.join(__dirname, mdPath, data[i]), 'utf-8') // join dir name, md folder path and filename and read its content
console.log('content:\n' + fileContent) // log its content
}
I created a folder ./md, containing the files one.md, two.md, three.md. The code above logs their content just fine.
>> node .\foo.js
file names [ 'one.md', 'three.md', 'two.md' ]
file name: one.md
content:
# one
file name: three.md
content:
# three
file name: two.md
content:
# two
Note that there is no error handling for anything that could go wrong with reading files.

Remove or change original data from stream Nodejs

I have a code to write a hash to the file from text of another file, but the problem is that in resulting file is written not only hash, but also the original text.
For example: if content of source file qwerty a got in result file qwertyd8578edf8458ce06fbc5bb76a58c5ca4, but i need just d8578edf8458ce06fbc5bb76a58c5ca4.
const fs = require('fs');
const crypto = require('crypto');
const hash = crypto.createHash('MD5');
const readData = fs.createReadStream('./task1/input.txt');
const writeData = fs.createWriteStream('./task1/output.txt');
readData.on('data', (chunk) => {
hash.update(chunk);
});
readData.on('end', () => {
const resultHash = hash.digest('hex');
writeData.end(resultHash);
console.log(resultHash);
});
readData.pipe(writeData);
How i can fix this? Thanks.
If you want to hash a stream, thats super easy as hash is itself a stream ( a Transform stream). Just pipe your input into it, and pipe the resulting hash into your output:
const fs = require('fs');
const crypto = require('crypto');
const hash = crypto.createHash('MD5');
const readData = fs.createReadStream('./task1/input.txt');
const writeData = fs.createWriteStream('./task1/output.txt');
readData.pipe(hash).pipe(writeData);
Reference

Uncaught TypeError: fs.readFileSync is not a function in console

I using below code for reading file from my local system:
var fs = require('fs');
var text = fs.readFileSync("./men.text");
var textByLine = text.split("\n")
console.log(textByLine);
NOTE: fs is a nodejs module, you cannot use it in Browser.
Import the fs module,
readFileSync will provide you the Buffer
to use the split() function you have to convert the Buffer into String
var fs = require('fs')
var text = fs.readFileSync("./men.text");
var string = text.toString('utf-8') // converting the Buffer into String
var textByLine = string.split("\n")
console.log(textByLine);
▼ UPDATE ▼
Server-Side
fs is a nodejs built-in module, you cannot use it in Browser(Client-Side). Use fs in server-side to do the manipulation, get the data and format in required type, then you can render it with html, ejs many more.. templating engines
Here i have created a Nodejs Server using express, and from the browser hit the http://localhost:8000/ you will get the Array of Data
You can format your data and render it with the .ejs or html files using res.render
app.js
var express = require('express');
var app = express();
var fs = require('fs')
app.get('/', function (request, response) {
var text = fs.readFileSync("./men.text");
var string = text.toString('utf-8')
var textByLine = string.split("\n")
console.log(textByLine);
response.send(textByLine);
});
app.listen('8000');
Dummy Output:
To all who are still getting undefined function on there eletron apps :
The solution (at least for me) was to instead of doing :
const fs = require('fs');
I did :
const fs = window.require('fs');
And that fixed ALL the problemes I had.
var fs = require('fs');
var text = fs.readFileSync('./men.text', 'utf8');
var textByLine = text.split("\n");
console.log(textByLine);

Categories

Resources