Home > Article > Web Front-end > How to read nodejs file after uploading
In the process of website development, file upload is a very common function. As a server-side JavaScript language, Node.js has the characteristics of asynchronous and efficient, and it also has good performance in file uploading. But how to read the file after it is uploaded? Let’s analyze the solution step by step.
1. File upload
We use the third-party module multer
in Node.js to handle file upload. multer
The module is simple to use and powerful, and supports multiple settings such as file upload size, upload path, and upload quantity. Its basic usage is as follows:
const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); app.post('/file/upload', upload.single('file'), function(req, res, next){ // 处理上传的文件 })
multer
The module can set the upload directory to save the file to the specified location. In the above example, the file will be saved in the uploads
folder in the current working directory, and the uploaded file will be saved in this folder and assigned a random file name.
2. How to read the file after uploading?
After the file upload is completed, we need to read the file. Here we can use the Node.js core module fs
to achieve this. The fs
module provides a variety of methods for operating files, among which fs.readFile()
can be used to read the contents of uploaded files. fs.readFile()
The function needs to pass in the file path and a callback function. At the same time, you can also set the encoding method for reading files and convert the read byte data into text with a specified encoding. Here we use the default binary encoding method to read the file content.
const fs = require('fs'); const path = require('path'); app.post('/file/upload', upload.single('file'), function(req, res, next){ const fileName = req.file.filename; // 上传时的文件名 const filePath = path.join(__dirname, 'uploads', fileName); // 上传后的文件保存路径 fs.readFile(filePath, function(err, data) { if (err) { console.error(err); res.status(500).send('文件读取失败'); } else { res.status(200).send(data); } }); })
In the above code, first get the uploaded file name, and then construct the file saving path based on the file name. Then, use the fs.readFile()
method to read the file content, and make corresponding operations based on the reading results. If the read fails, a 500 status code is returned; if the read is successful, the read file content is returned.
3. Summary
File uploading and file reading are common functions in website development. Use multer
and fs## in Node.js #Modules can easily implement these functions. When reading files, you need to pay attention to handling possible errors to prevent the application from crashing due to errors.
The above is the detailed content of How to read nodejs file after uploading. For more information, please follow other related articles on the PHP Chinese website!