Here's a Node.js code example that reads a file and converts its contents from a string to an array:

const fs = require('fs');

fs.readFile('file.txt', 'utf8', function(err, data) {
  if (err) throw err;
  const dataArray = data.split('
');
  console.log(dataArray);
});

This code utilizes the 'fs' module in Node.js to read a file named 'file.txt' located in the current working directory. The second argument, 'utf8', specifies the encoding of the file, ensuring it's read as a string.

The 'readFile' function uses a callback function as its second argument. This callback is executed once the file has been read. Within the callback, the file data is processed using the 'split' method, dividing it into an array of strings based on the newline character (' '). This resulting array is then printed to the console.

Node.js: Read File and Convert String to Array

原文地址: https://www.cveoy.top/t/topic/njkK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录