This is the 24th day of my participation in the August Text Challenge.More challenges in August
A little feeling
I’ve noticed that many of my friends in Node development would react in one of two ways if they encountered a requirement they hadn’t done before:
- The first performance is to ask Baidu, better ask Google
- The second expression is to ask others
Asking someone else first can lead to an idea, but sometimes it can also make you more ambiguous, because you have no prior knowledge of the API and have not given basic thought to how to implement it. In this case, forcing someone else’s idea on you will not help you achieve your requirements
And direct Baidu or Google, in fact, and ask others the same, get other people’s ideas, the only difference is that in this search process, you will think, the formation of basic thinking.
But based on my own experience, I found a problem:
Often, when we have a requirement and we have no idea where to start, we have searched it in our head and are left stranded when our knowledge base does not find anything relevant to implement the requirement.
Here’s an example:
So I was confused, I didn’t know what to do, so I could only ask Baidu, and then they said, FS can write files, at this time I looked up fs API, and then in CSDN, think whether all kinds of look, well, it seems to understand, in fact, this is a CV process, after you realize this requirement, deliciously off work
So when you are waiting for the bus on the road, do you think you need to complete this day? Can you independently tell what FS does? How many common methods does it have? How does it all work? You’ve been working here all day. Did you learn anything new?
So, the real problem is that MY knowledge is not broad enough or deep enough to completely take care of everyday development needs. If I had a basic impression or knowledge of fs as a file system, I would have just read the documentation.
Get to the point
Node fs file system is a very common module, which can be used to easily add, delete, change, check, read, and write files and folders.
Fs requires no additional installation, just import, and FS provides a variety of ways to import and use.
- Callback-based asynchrony
import * as fs from 'fs';
// or
import { unlink } from 'fs';
Copy the code
Because operations such as file reading and writing are asynchronous, callback functions are used. Node follows the ERROR first principle, and the first argument in the callback is usually an ERROR object, which is used to catch exceptions while operating. If there is no exception, the first argument is null or undefined
unlink('./hello.txt'.(err) = > {
if (err) throw err;
console.log('successfully deleted ./hello.txt');
});
Copy the code
- Asynchronous based on the Promise API
import * as fs from 'fs/promises';
// or
import { unlink } from 'fs/promises';
Copy the code
Promise made it possible to write asynchronous code in synchronous logic, largely eliminating callback hell. Simple to write, the Promise API couldn’t catch exceptions and relied on try{}catch(){} statements.
try {
await unlink('./hello.text');
console.log('successfully deleted ./hello.text');
} catch (error) {
console.error('there was an error:', error.message);
}
Copy the code
Using the Promise API requires additional caution:
The Promise API uses the underlying Node.js thread pool to perform file system operations outside of the event loop thread. These operations are neither synchronous nor thread-safe. You must be careful when performing multiple concurrent changes to the same file, or you may corrupt the data.
- Synchronous writing
The synchronized code blocks the Node.js event loop and subsequent JavaScript code from executing until the synchronized operation is complete. So in general, use it with or without caution.
import { unlinkSync } from 'fs';
try {
unlinkSync('./hello.text');
console.log('successfully deleted ./hello.text');
} catch (err) {
console.error('there was an error:', error.message);
}
Copy the code
Export CSV
In the program development, it is often necessary to export data to CSV, TXT, or even PDF files for users to view or share data.
Now, let’s use FS to implement how to export data to CSV files.
- Create a folder node-csv
- Create a new file, demo.js, in the folder
- Open with an editor and edit demo.js
const { promises: { readFile, writeFile, mkdir } } = require('fs');
(async() = > {// Create simulated data
let list = []
for (let i = 0; i < 10; i += 1) {
list.push({
id: i,
name: 'Ming'.age: 18.address: Beijing Haidian Academy of Agricultural Sciences.phone: '13313366789'})},/* * generates header, \ufeff is to prevent garbled * CSV with ', 'column swap,' \n 'newline */
let title = Object.keys(list[1])
let csvContent = '\ufeff' + title.join(', ') + '\n'
// Add a table body
list.forEach((item, index) = > {
let c = Object.values(item).join(', ') + '\n'
csvContent += c
})
// Build folder stores the generated files
await mkdir('download')
// Generate a CSV file
await writeFile('./download/data.csv', csvContent)
/ / generated JOSN
await writeFile('./download/data.json'.JSON.stringify(list))
console.log('File generated successfully, open download to check')
})()
Copy the code
Run the following command in CMD or terminal
node demo
Copy the code
When you see a reminder like this
ExperimentalWarning: The Fs. promises API is experimental File generated successfully, open download to checkCopy the code
Then, open the Download folder and view the generated CSV and JSON files.
If you want to learn about FS promises, or how to generate TXT, click here
Code word is not easy, send a good ~ ~