简体   繁体   中英

Read txt file, run text filter using a Node module and write to a new .txt file using NodeJS

I am trying to try out open a file, run a filter from an NPM module and then write the result as new.txt file.

It works, but the output is blank. Does the file need to be streamed in both read and write process?

Here is the code:

async function main() {
    const fs = require('fs');
    const parBuild = require('paragraph-builder');
    const util = require('util');
    const filename = "Guardian-Yvette-TextBlock.txt";
    var data;

    //const readFile = util.promisify(fs.readFile);

    fs.readFile('Guardian-Yvette-TextBlock.txt', 'utf8', function(err, text) {
      if (err) throw err;
      console.log(text);
  });

    const sourceTXT = await readFile(filename, 'utf8')
      .then((text) => {
        console.log('TXT File:', text);
      })
      .catch((err) => {
        console.log('Error', err);
      });

    var resultText = parBuild.toString(sourceTXT);

    const writeTXTFile = util.promisify(fs.writeFile);
    await writeTXTFile(filename + "-para.txt", resultText, 'utf-8');
    console.log('Paragraph TXT file created and written to local directory');
  }
  main().catch(console.error);

These are the text (.txt) files from the newspaper article I am working with.

https://friendly-mccarthy-005993.netlify.app/

Uncomment this //const readFile = util.promisify(fs.readFile); on line 8 and check a cleaner solution:

<!-- language: javascript -->
const fs = require('fs');
const parBuild = require('paragraph-builder');
const util = require('util');

async function main() {
  const filename = "Guardian-Yvette-TextBlock.txt";

  const readFile = util.promisify(fs.readFile);
  const content = await readFile(filename, 'utf8')

  const resultText = parBuild.toString(content);

  const writeFile = util.promisify(fs.writeFile);
  await writeFile(filename + "-para.txt", resultText, 'utf-8');
  console.log('Paragraph TXT file created and written to local directory');
}

try {
  main()
} catch (error) {
  console.error(error);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM